package cn.com.generaldata.os.ws.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.util.CommonUtils;
import org.jsoup.helper.StringUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.generaldata.jsme_indicator_system.entity.ReportTypeLimit;
import cn.com.generaldata.jsme_indicator_system.entity.StatSystem;
import cn.com.generaldata.jsme_indicator_system.entity.SummaryReportType;
import cn.com.generaldata.jsme_indicator_system.vo.reportdesigner.ReportExcelSectionVO;
import cn.com.generaldata.os.action.PmAction;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.exporter.Exporter;
import cn.com.generaldata.os.importer.Importer;
import cn.com.generaldata.os.newpojo.ReportVersion;
import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.Pm;
import cn.com.generaldata.os.pojo.ReportDetail;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.pojo.mvc.Row;
import cn.com.generaldata.os.result.ReportVerityQueryResult;
import cn.com.generaldata.os.result.ReportVersionYearRangeResult;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.HistoryService;
import cn.com.generaldata.os.service.common.MarkingService;
import cn.com.generaldata.os.service.common.ReportTemplateService;
import cn.com.generaldata.os.service.common.ReportTypeService;
import cn.com.generaldata.os.service.common.RoleService;
import cn.com.generaldata.os.service.common.StatSystemService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.UnitService;
import cn.com.generaldata.os.service.intf.ReportEIServiceInterface;
import cn.com.generaldata.os.service.intf.ReportServiceInterface;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.util.CacheManager;
import cn.com.generaldata.os.util.CommonUtil;
import cn.com.generaldata.os.vo.BillboardVO;
import cn.com.generaldata.os.vo.DynamicReportVO;
import cn.com.generaldata.os.vo.ReportAttachVO;
import cn.com.generaldata.os.vo.ReportHistoryVO;
import cn.com.generaldata.os.vo.ReportMarkingVO;
import cn.com.generaldata.os.vo.ReportPerformVO;
import cn.com.generaldata.os.vo.ReportTypeVO;
import cn.com.generaldata.os.vo.ReportVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UserVO;
import cn.com.generaldata.os.vo.VersionVO;
import cn.com.generaldata.os.ws1.ModelSend;
import cn.com.generaldata.os.zip.ZipCompressor;

import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;

@SuppressWarnings("unused")
@InjectName
@Component
public class ReportWS {

	@Autowired
	private ReportTypeService reportTypeService;
	@Autowired
	private ReportServiceInterface reportService;

	@Autowired
	private PmAction pmWS;

	@Autowired
	private AutoPushingWS aotoWS;
	@Autowired
	private BillboardWS billWS;
	@Autowired
	private ReportEIServiceInterface reportEIService;
	@Autowired
	private UserService userService;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private AreaService areaService;

	private List<Integer> yearList;

	private List<cn.com.generaldata.os.vo.RoleVO> roleList;

	private BaseDAOInterface<SystemCodedic> sysCodedicDAO;
	@Autowired
	private ReportTemplateService reportTmplate;

	@Autowired
	private SqlTemplate indicatorSystemSqlTemplate;

	@Autowired
	private StatSystemService statSystemService;

	@Autowired
	private UnitService unitService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private IndustryWS industryWS;

	@Autowired
	private UnitWS unitWS;

	@Autowired
	private VersionWS versionWS;

	@Autowired
	private NutDao dao;

	@Autowired
	private CacheManager cacheManager;
	private final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM");
	/**
	 * 导出报表生成的文件所在的目录.
	 */
	@Value("${excelDownPath}")
	private String excelDownPath;
	@Value("${serviceIp}")
	public String ip;
	@Value("${servicePort}")
	public String port;
	@Value("${serviceName}")
	public String serviceName;

	private static Logger log = LoggerFactory.getLogger(ReportWS.class);

	private MarkingService markingService;
	private Exporter exporter;
	private Date date;
	List<String> urlList;
	private String url;

	// 配置文件
	private final Properties properties = new Properties();
	private final Properties properties2 = new Properties();
	private static final String EXPORT_ROOT_DIR = "D:";
	private static final String EXPORT_ROOT_DIR_1 = "apachetomcat6018/webapps/jsme-das-lan/files";
	private static final String EXPORT_FILE = "export_report";
	private static final String EXPORT_FILE_BACKUP = "export_report_backup";

	@PostConstruct
	public void init() {
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			log.error("加载配置文件出错", ex);
		}

		java.io.InputStream inputstream2 = getClass().getResourceAsStream("/global_conf.properties");
		try {
			properties2.load(inputstream2);
		} catch (Exception ex) {
			log.error("加载配置文件出错", ex);
		}
		// 获取当前日期
		Calendar cal = Calendar.getInstance();
		int tyear = cal.get(Calendar.YEAR);

		yearList = new ArrayList<Integer>();
		for (int i = tyear; i >= 1997; i--) {
			yearList.add(i);
		}

	}

	public ResultVO<ReportVO> queryReports(String userId, Short checkStatus, String reportTypeNo,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	@At("/data/modify")
	public String modiAttachDisposal(@Param("attachId") String attachId, @Param("attachDisposal") String attachDisposal) {
		reportService.modiAttachDisposal(attachId, attachDisposal);
		return "success";
	}

	@At("/data/edit")
	@Ok("jsp:/static/ocean/data/edit")
	public void editAttachDisposal(@Param("id") String attachId, HttpServletRequest request) {
		ReportAttachVO reportAttach = queryReportAttachById(attachId);
		request.setAttribute("reportAttach", reportAttach);
	}

	/**
	 * 处理完成.
	 */
	@At("/data/deal")
	@Ok("json")
	public String modiReportAttachsDisposal(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		reportService.modiReportAttachsDisposal(idArray);
		return "{id:0}";
	}

	// 查询当前企业所有的上传附件
	@At("/data/transferReportList")
	@Ok("jsp:/static/ocean/data/transferReportList")
	public ResultVO<ReportAttachVO> queryReportAttach(@Param("searchDate") Date searchDate,
			@Param("endDate") Date endDate, Integer pageNum, HttpSession session) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		String loginName = voUser.getId();

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		// 如果查询用户ID不为空，就是企业查询，管理部门传null查询全部
		if (StringUtils.isNotBlank(loginName)) {
			User userById = userService.queryUserById(loginName);
			Filter filter2 = new Filter();
			filter2.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", userById.getUserUnit().getId()));
			cn.com.generaldata.os.paging.Result result = userService.queryUsers(filter2, null);
			if (result != null) {
				List<User> operationResult = (List<User>) result.getOperationResult();
				String[] uids = new String[operationResult.size()];
				for (int i = 0; i < operationResult.size(); i++) {
					uids[i] = operationResult.get(i).getId();
				}
				if (!(operationResult.size() > 0)) {
					uids = new String[] { "" };
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "userId", uids));
			} else {
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "userId", loginName));
			}
		}
		// 状态为3的是管理部门发送通知的附件
		filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "isDisposal", 3));
		if (searchDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(searchDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "sysCreateDate", calendar.getTime()));
		}

		if (endDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.LT, "sysCreateDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(new Integer(1), ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReportAttach(reportService.queryReportAttach(filter, page));
	}

	// 查询当前单位下级所有的上传附件

	@At("/data/list")
	@Ok("jsp:/static/ocean/data/dealReportList")
	public ResultVO<ReportAttachVO> queryHandleAttach(@Param("searchDate") Date searchDate,
			@Param("endDate") Date endDate, @Param("p") Integer pageNum, HttpSession session) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userAreaId = voUser.getUserAreaId();

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		String hql = "from ReportAttach as ra where 1=1";
		HashMap map = new HashMap();
		// 如果查询用户ID不为空，就是企业查询，管理部门传null查询全部
		if (StringUtils.isNotBlank(userAreaId)) {
			hql += " and exists (select u.id from User as u where u.id=ra.userId and exists(select a.id from Area as a where a.id=u.area.id and a.areaCode is not null and a.parentId=:userAreaId))";
			map.put("userAreaId", userAreaId);

		}
		// 状态为3的是管理部门发送通知的附件
		// filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "isDisposal",
		// 3));
		hql += " and isDisposal<>3";
		if (searchDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(searchDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			// filter.addRule(new FilterRule(FilterConstant.GE, "sysCreateDate",
			// calendar.getTime()));
			hql += " and sysCreateDate >=:startDate";
			map.put("startDate", calendar.getTime());
		}

		if (endDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			hql += " and sysCreateDate <:endDate";
			map.put("endDate", calendar.getTime());

			// System.out.println(calendar.getTime());
			// filter.addRule(new FilterRule(FilterConstant.LT, "sysCreateDate",
			// calendar.getTime()));

		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(new Integer(1), ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReportAttach(reportService.queryReportAttachByHql(hql, map, page));
	}

	/**
	 * 下载文件.
	 * 
	 * @param fileName
	 *            文件名
	 * @param response
	 * @param context
	 */
	@At("/data/download")
	@Ok("void")
	public void downloadLocal(@Param("id") String id, HttpServletResponse response, HttpServletRequest request,
			ServletContext context) {

		File file = new File(properties.getProperty("fileUploadPath").trim()); // 路径是存文件的路径

		ReportAttachVO reportAttach = queryReportAttachById(id);

		String pathName = reportAttach.getAttachPathname();
		String fileName = reportAttach.getAttachFilename();

		// 导出路径
		String folderPath = properties.getProperty("fileUploadPath").trim() + pathName;

		// 读到流中
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(folderPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		// 设置输出的格式
		response.reset();
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

		// 循环取出流中的数据
		byte[] b = new byte[64 * 1024];
		int len;
		try {
			while ((len = inStream.read(b)) > 0) {
				response.getOutputStream().write(b, 0, len);
				response.getOutputStream().flush();
			}
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@At("/audit/mutiExport")
	@Ok("void")
	public void mutiExport(@Param("checkStatus") String checkStatus, @Param("repId") String reporTypeId,
			@Param("startingReportDate") Date startingReportDate, @Param("endingReportDate") Date endingReportDate,
			@Param("flag") String flag, @Param("showSum") boolean showSum, @Param("repNewId") String newTypeId,
			@Param("year") String year, HttpServletRequest request, HttpServletResponse response) {

		UserVO user = (UserVO) request.getSession().getAttribute("user");
		String userId = user.getId();

		cn.com.generaldata.os.newpojo.ReportType reportType = reportService.queryReportTypeById(reporTypeId);

		DynamicReportVO verifyReortDetail = reportService.getVerifyReortDetail(userId, checkStatus, reporTypeId,
				startingReportDate, endingReportDate, flag, showSum, newTypeId, year);
		String excel = "";
		if (verifyReortDetail.getBody() != null && verifyReortDetail.getBody().size() > 0) {
			excel = reportService.exportReportExcel(verifyReortDetail, reportType.getTypeName());
			// 导出路径
			String filePath = excelDownPath + File.separator + excel;
			CommonUtil.downloadFile(filePath, "导出汇总报表.zip", response);
		}
	}

	public String importUnitInfo(byte[] content, String fileName, String fileType, String typeId, String year) {

		String[] split = fileName.split(fileType);
		String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("上传文件出错", e);
			}
			String importIndicator = reportService.importUnitInfo(file, typeId, year);

			return importIndicator;
		}
		return null;
	}

	@At("/audit/toVerify")
	@Ok("jsp:/static/ocean/audit/mutiVerifyList")
	public void toVerify(@Param("checkStatus") String checkStatus, @Param("reporTypeId") String reporTypeId,
			@Param("startingReportDate") Date startingReportDate, @Param("endingReportDate") Date endingReportDate,
			@Param("flag") String flag, @Param("newTypeId") String newTypeId, @Param("year") String year,
			HttpServletRequest request) {
		request.setAttribute("checkStatus", checkStatus);
		request.setAttribute("reporTypeId", reporTypeId);
		request.setAttribute("startingReportDate", startingReportDate);
		request.setAttribute("endingReportDate", endingReportDate);
		request.setAttribute("flag", flag);
		request.setAttribute("newTypeId", newTypeId);
		request.setAttribute("year", year);
	}

	/**
	 * 审核报表
	 * @param checkStatus
	 * @param reporTypeId
	 * @param startingReportDate
	 * @param endingReportDate
	 * @param flag
	 * @param newTypeId
	 * @param year
	 * @param request
	 */
	@At("/audit/mutiVerify")
	@ResponseBody
	public ReportVerityQueryResult getVerifyReortDetail(@Param("checkStatus") String checkStatus,
			@Param("reporTypeId") String reporTypeId, @Param("startingReportDate") Date startingReportDate,
			@Param("endingReportDate") Date endingReportDate, @Param("flag") String flag,
			@Param("newTypeId") String newTypeId, @Param("year") String year, HttpServletRequest request) {
		UserVO user = (UserVO) request.getSession().getAttribute("user");
		String userId = user.getId();

		ReportVerityQueryResult result = new ReportVerityQueryResult();
		try {
			DynamicReportVO verifyReortDetail = reportService.getVerifyReortDetail(userId, checkStatus, reporTypeId,
					startingReportDate, endingReportDate, flag, false, newTypeId, year);
			Map map = new HashMap();
			map.put("Rows", verifyReortDetail.getBody());
			result.setQueryResult(Json.toJson(map));
			List<List<String>> headers = verifyReortDetail.getHeaders();
			if (headers != null && headers.size() > 0) {
				List<String> headList = headers.get(0);
				List<String> unitList = headers.get(1);
				result.setHead(headList);
				result.setUnit(unitList);
			} else {
				result.setHead(null);
				result.setUnit(null);
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setDefaultError();
			return result;
		}
	}

	public String importReportMulti(String reportProxyId, File file, String fileName, String fileType) {
		String error = "";
		String[] split = fileName.split("_");
		// 分为三段，一为日期，二是单位，三是表名
		if (split.length == 3) {
			String time = split[0];
			String year = time;
			int yearIndex = time.indexOf("年");
			if (yearIndex == -1) {
				// 年份不是XXXX格式
				if (time.length() != 4) {
					error = "日期格式缺少年";
				}
			} else {
				year = time.substring(0, yearIndex);
			}
			if (error == "") {
				Calendar date = Calendar.getInstance();
				int monthValue = date.get(Calendar.MONTH);
				String month = String.valueOf(monthValue + 1);
				int monthIndex = time.indexOf("月");
				if (monthIndex != -1) {
					if (yearIndex != -1) {
						month = time.substring(yearIndex + 1, monthIndex);
					} else {
						month = time.substring(monthIndex);
					}
				}
				String quarter = "1";
				if (monthValue < 3) {
					quarter = "1";
				} else if (monthValue >= 3 && monthValue < 6) {
					quarter = "2";
				} else if (monthValue >= 6 && monthValue < 9) {
					quarter = "3";
				} else if (monthValue >= 9) {
					quarter = "4";
				}
				int quarterIndex = time.indexOf("季度");
				if (quarterIndex != -1) {
					quarter = time.substring(quarterIndex - 1, quarterIndex);
					if ("1".equals(quarter)) {
						month = "1";
					} else if ("2".equals(quarter)) {
						month = "4";
					} else if ("3".equals(quarter)) {
						month = "7";
					} else if ("4".equals(quarter)) {
						month = "10";
					}
				}
				String dateTime = year + "/" + month;
				if (Integer.valueOf(month) < 10) {
					dateTime = year + "/0" + month;
				}
				String unitName = split[1];
				Unit unit = unitService.getUnitId(unitName);
				if (unit != null) {
					String reportSplit = split[2];
					int lastIndexOf = reportSplit.lastIndexOf("-");
					String name = reportSplit;
					String typeNo = "";
					// 有表号
					if (lastIndexOf != -1) {
						// 表号
						typeNo = reportSplit.substring(0, lastIndexOf);
						name = reportSplit.substring(lastIndexOf + 1);
					}
					String[] splitName = name.split(fileType);
					String typeName = splitName[0];
					cn.com.generaldata.os.newpojo.ReportType reportType = reportService.getTypeId(typeNo, typeName,
							dateTime);
					if (reportType == null) {
						error = "年份与报表模板不符";
					} else {
						// 暂时不用批量导入
						error = importReport(unit.getId(), reportProxyId, reportType.getId(), reportType.getTypeTime(),
								reportType.getTypeYearTime(), dateTime, "", reportType.getVersionId().toString(),
								quarter, file, "2");
					}
				} else {
					error = "不存在该单位名称";
				}
			}
		} else {
			error = "报表名称格式不符";
		}
		return error;

	}

	/**
	 * 导入报表
	 * 
	 * @param reportOperatorId
	 * @param reportProxyId
	 * @param reportTypeId
	 * @param timeType
	 * @param yearType
	 * @param timeDate
	 * @param unitIndustryId
	 * @param reportVersion
	 * @param quarterDate
	 * @param content
	 * @param fileName
	 * @param fileType
	 * @return
	 * @throws IOException
	 */

	public String importReport(String reportOperatorId, String reportProxyId, String reportTypeId, String timeType,
			String yearType, String timeDate, String unitIndustryId, String reportVersion, String quarterDate,
			File file, String status) {

		// 获取报表季度
		String lasttimeQuarterDate = "第零季度";
		String quarterValue = "1";
		if (quarterDate.equals("1")) {
			quarterDate = "第一季度";
			quarterValue = "1";
		} else if (quarterDate.equals("2")) {
			quarterDate = "第二季度";
			lasttimeQuarterDate = "第一季度";
			quarterValue = "2";
		} else if (quarterDate.equals("3")) {
			quarterDate = "第三季度";
			lasttimeQuarterDate = "第二季度";
			quarterValue = "3";
		} else if (quarterDate.equals("4")) {
			quarterDate = "第四季度";
			lasttimeQuarterDate = "第三季度";
			quarterValue = "4";
		}
		// cn.com.generaldata.os.pojo.mvc.Report report = new
		// cn.com.generaldata.os.pojo.mvc.Report();

		// 报表所属用户和操作用户
		if (reportOperatorId == null) {
			return null;
		}
		if (reportTypeId == null) {
			return null;
		}
		Unit unit = unitService.queryUnitById(reportOperatorId);
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", unit.getId()));
		filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "role.id", "1"));
		cn.com.generaldata.os.paging.Result queryUsers = userService.queryUsers(filter, null);
		User user = new User();
		List<User> userList = (List<User>) queryUsers.getOperationResult();
		// Set<User> users = unit.getUsers();
		// if (users == null || !(users.size() > 0)) {
		// return null;
		// } else {
		user = userList.get(0);
		// }
		// model.put("user", user);
		cn.com.generaldata.os.newpojo.ReportType rType = reportService.queryReportTypeById(reportTypeId);
		// model.put("reportType", rType);

		String limit = properties2.getProperty("limit").trim();
		Calendar date = Calendar.getInstance();
		// 正确填报时间
		Calendar dateOK = Calendar.getInstance();
		// 年
		String yearValue = timeDate.substring(0, 4);
		// 月
		String monthValue = timeDate.substring(5, 7);
		// 不能提前上报
		if (date.get(Calendar.YEAR) < Integer.valueOf(yearValue)) {
			return "不能提前上报";
		}
		// 获取报表年属性
		String typeYear = rType.getTypeYearTime();
		if (!StringUtil.isBlank(yearType))
			typeYear = yearType;
		timeType = rType.getTypeTime();

		// 是迟报就不判断了
		if (!"2".equals(status) && "true".equals(limit)) {
			// Integer unitLevel =
			// userService.getUnitLevel(user.getUserUnit().getId());
			List<ReportTypeLimit> limitList = reportService.queryReportLimit(rType.getStatSystem(), reportTypeId,
					rType.getTypeTime(), typeYear);
			// 催报信息
			Integer timeBill = reportService.queryBillByReport(reportTypeId, user.getUserUnit().getId(), timeType,
					typeYear, timeDate, quarterDate);
			if (timeBill == null) {
				timeBill = new Integer(0);
			}
			for (ReportTypeLimit reportLimit : limitList) {
				Integer startDay = reportLimit.getStartDay();
				Integer endDay = reportLimit.getEndDay();
				Integer startMonth = reportLimit.getStartMonth();
				Integer endMonth = reportLimit.getEndMonth();
				// 月报(下月1日+延期)
				if ("0".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					// && (unitLevel == reportLimit.getLevel() ||
					// reportLimit.getLevel() == null)) {
					dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
					dateOK.set(Calendar.MONTH, Integer.valueOf(monthValue));
					dateOK.set(Calendar.DATE, startDay);
					if (date.before(dateOK)) {
						return "不能提前上报";
					}
					dateOK.set(Calendar.DAY_OF_YEAR, dateOK.get(Calendar.DAY_OF_YEAR) + endDay - startDay + timeBill);
					if (date.after(dateOK)) {
						return "不能提前上报";
					}
					break;
				}
				// 季报
				else if ("2".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					// && (unitLevel == reportLimit.getLevel() ||
					// reportLimit.getLevel() == null)) {
					if (Integer.valueOf(quarterValue) == 1) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 3);
					} else if (Integer.valueOf(quarterValue) == 2) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 6);
					} else if (Integer.valueOf(quarterValue) == 3) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 9);
					} else if (Integer.valueOf(quarterValue) == 4) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue) + 1);
						dateOK.set(Calendar.MONTH, 0);
					}
					dateOK.set(Calendar.DATE, startDay);
					if (date.before(dateOK)) {
						return "不能提前上报";
					}
					dateOK.set(Calendar.DAY_OF_YEAR, dateOK.get(Calendar.DAY_OF_YEAR) + endDay - startDay + timeBill);
					if (date.after(dateOK)) {
						return "不能提前上报";
					}
					break;
				}
				// 年报
				else if ("1".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					// && (unitLevel == reportLimit.getLevel() ||
					// reportLimit.getLevel() == null)) {
					// 上半年报或全年报
					if ("2".equals(typeYear) && reportLimit.getTypeYearTime().equals(typeYear)) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue) + 1);
						dateOK.set(Calendar.MONTH, startMonth - 1);
						dateOK.set(Calendar.DATE, startDay);
						if (date.before(dateOK)) {
							return "不能提前上报";
						}
						dateOK.set(Calendar.MONTH, endMonth - 1);
						dateOK.set(Calendar.DATE, endDay + timeBill);
						if (date.after(dateOK)) {
							return "不能提前上报";
						}
					} else if ("1".equals(typeYear) && reportLimit.getTypeYearTime().equals(typeYear)) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, startMonth - 1);
						dateOK.set(Calendar.DATE, startDay);
						if (date.before(dateOK)) {
							return "不能提前上报";
						}
						dateOK.set(Calendar.MONTH, endMonth - 1);
						dateOK.set(Calendar.DATE, endDay + timeBill);
						if (date.after(dateOK)) {
							return "不能提前上报";
						}
					}
					continue;
				}
			}
		}
		// 判断当前用户的报表与报表时段是否存在，存在不得保存
		if (reportService.isReportTimeType(user, rType.getId(), timeType, typeYear, timeDate, quarterDate,
				reportVersion)) { // 表示已经存在
			return "已经存在";
		}
		ReportExcelSectionVO sectionInfo = reportTmplate.getReportExcelSectionInfo(file, reportTypeId);
		int reportFootEndRow = sectionInfo.getReportFootEndRow();
		int reportFootStartRow = sectionInfo.getReportFootStartRow();
		int tableBodyEndRow = sectionInfo.getTableBodyEndRow();
		int tableBodyStartRow = sectionInfo.getTableBodyStartRow();
		if (reportFootEndRow == -1 || reportFootStartRow == -1 || tableBodyEndRow == -1 || tableBodyStartRow == -1)
			return "报表错误!";
		// sectionInfo.getReportFootEndRow();
		try {
			String reportName = reportService.import_report(user, reportProxyId, rType, timeType, typeYear, timeDate,
					unitIndustryId, reportVersion, quarterDate, file, sectionInfo);
			if (StringUtils.isNotBlank(reportName)) {
				Files.rename(file, reportName + ".xls");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("报表错误", e);
			return null;
		}

		return "导入成功";
	}

	@At("/data/uploadFile")
	@POST
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("jsp:/static/ocean/unit/uploadOk")
	public void uploadFile(@Param("uploadFile") TempFile uploadFile, ServletContext context,
			HttpServletRequest request, @Param("attachExplain") String attachExplain, String status, HttpSession session)
			throws IOException {
		if (uploadFile == null) {
			request.setAttribute("msg", "请选择文件。");
			return;
		}
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		String loginName = voUser.getId();
		String userUnit = voUser.getUserUnit();
		String fileName = uploadFile.getFile().getName();
		String fileType = uploadFile.getMeta().getName();

		String result = ""; // 添加失败
		ReportAttachVO reportAttach = new ReportAttachVO(); // 文件附件实体
		String folderPath = properties.getProperty("fileUploadPath").trim();

		String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String ext = uploadFile.getMeta().getFileExtension();
		String newFileName = voUser + timeStr + ext;

		String oldFileName = uploadFile.getMeta().getFileLocalName();

		moveFile(uploadFile.getFile(), folderPath + newFileName);

		// reportAttach.setAttachId(pathName);
		reportAttach.setAttachFilename(oldFileName);
		reportAttach.setUserId(loginName);
		reportAttach.setUserUnit(userUnit);
		reportAttach.setSysCreateDate(new Date());

		if (StringUtils.isNotBlank(status)) {
			reportAttach.setIsDisposal(3);// 通知中的附件
		} else {
			reportAttach.setIsDisposal(0); // 为处理的附件
		}

		reportAttach.setAttachPathname(newFileName);
		reportAttach.setAttachExplain(attachExplain);
		result = this.addReportAttachments(reportAttach); // 将上传的附件信息保存到附件表中
		// result = 1;

		// stream.close();
		request.setAttribute("msg", "上传成功");
	}

	private boolean moveFile(File source, String target) {

		if (source == null || target == null || "".equals(target)) {
			return false;
		}

		int dot = target.lastIndexOf("\\");
		String floder = target.substring(0, dot);
		File fl = new File(floder);
		if (!fl.exists()) {
			fl.mkdirs();
		}

		File f = new File(target);

		if (!f.exists()) {
			return source.renameTo(f);
		}

		return false;
	}

	private ReportAttachVO toVoReportAttach(cn.com.generaldata.os.pojo.ReportAttach pReportAttach) {

		if (pReportAttach != null) {
			return new ReportAttachVO(pReportAttach.getAttachId(), pReportAttach.getAttachFilename(),
					pReportAttach.getUserId(), pReportAttach.getUserUnit(), pReportAttach.getSysCreateDate(),
					pReportAttach.getIsDisposal(), pReportAttach.getAttachPathname(), pReportAttach.getAttachExplain());
		}
		return null;
	}

	public ResultVO<ReportAttachVO> queryReportAttachList(String ids) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		if (StringUtils.isNotBlank(ids)) {
			String[] split = ids.split(",");
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "attachId", split));
		}
		return toVoResultReportAttach(reportService.queryReportAttach(filter, null));
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportAttachVO> toVoResultReportAttach(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportAttachVO> result = new ResultVO<ReportAttachVO>();

		List<ReportAttachVO> reportAttachs = new ArrayList<ReportAttachVO>();
		for (cn.com.generaldata.os.pojo.ReportAttach pReportAttach : (List<cn.com.generaldata.os.pojo.ReportAttach>) pResult
				.getOperationResult()) {
			ReportAttachVO voReportAttach = toVoReportAttach(pReportAttach);
			if (voReportAttach != null) {
				reportAttachs.add(voReportAttach);
			}
		}
		result.setOperationResult(reportAttachs);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	// 查询当前ID的上传附件

	public ReportAttachVO queryReportAttachById(String id) {
		cn.com.generaldata.os.pojo.ReportAttach attachById = reportService.queryReportAttachById(id);
		return toVoReportAttach(attachById);
	}

	// 添加附件文件

	public String addReportAttachments(ReportAttachVO reportAttach) {
		return reportService.addReportAttachments(this.toPojoReportAttach(reportAttach));
	}

	public cn.com.generaldata.os.pojo.ReportAttach toPojoReportAttach(ReportAttachVO reportAttach) {
		return new cn.com.generaldata.os.pojo.ReportAttach(null, reportAttach.getAttachFilename(),
				reportAttach.getUserId(), reportAttach.getUserUnit(), reportAttach.getSysCreateDate(),
				reportAttach.getIsDisposal(), reportAttach.getAttachPathname(), reportAttach.getAttachExplain());
	}

	/**
	 * 批量删除附件.
	 */
	@At("/data/deleteMany")
	@Ok("json")
	public String delReportAttachsDisposal(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		reportService.removeReportAttachs(idArray);
		return "{id:0}";
	}

	// 根据用户地区查找报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByArea(String userId, String userAreaId, Short checkStatus,
			String reportSystem, String reportTypeNo, String reportVersion, Date startingReportDate,
			Date endingReportDate, Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(userAreaId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		} else if (!StringUtils.isNotBlank(reportTypeNo) && StringUtils.isNotBlank(reportSystem)) {

			Filter typeFilter = new Filter();

			StatSystem ss = statSystemService.getStatSystemByName(reportSystem.trim());
			if (ss != null) {
				typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", ss.getId()));
			}

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}
		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportService.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	public List<SystemCodedic> getSysCode(Filter sysFilter) {
		// sysFilter.addRule(new FilterRule(FilterConstant.EQUAL, "code",
		// pReportType.getStatSystem().toString()));
		// sysFilter.addRule(new FilterRule(FilterConstant.EQUAL, "section",
		// "10012"));
		List<SystemCodedic> find = sysCodedicDAO.find(SystemCodedic.class, sysFilter, null);
		// if (find != null && find.size() > 0) {
		// SystemCodedic systemCodedic = find.get(0);
		// type = systemCodedic.getCodeName();
		// }
		return find;
	}

	// 取得版本类型（三个）
	public List<SystemCodedic> queryType() {
		List<SystemCodedic> list = Lists.newArrayList();
		Map<String, String> statSystems = statSystemService.getStatSystemMap();
		for (Entry<String, String> entry : statSystems.entrySet()) {
			SystemCodedic sc = new SystemCodedic();
			sc.setCode(entry.getKey());
			sc.setCodeName(entry.getValue());
			list.add(sc);
		}
		return list;
	}

	public List<ReportTypeVO> queryTypeNo(Integer type) {
		List<String> queryTypeNo = reportService.queryTypeNo(type);
		List<ReportTypeVO> list = Lists.newArrayList();
		for (String typeNo : queryTypeNo) {
			if (typeNo == null) {
				continue;
			}
			ReportTypeVO rt = new ReportTypeVO();
			rt.setTypeNo(typeNo);
			list.add(rt);
		}
		return list;
	}

	// 根据用户地区查找将要导出的报表 (省级用户导出报表，包括通过的和驳回的)
	public ResultVO<ReportVO> queryExportReportsByArea(String userId, String userAreaId, Short checkStatus,
			String reportTypeNo, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(userAreaId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportService.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	// 自加， 根据用户地区和单位查找报表
	public ResultVO<ReportVO> queryReportsByAreaAndUnit(String userId, String userAreaId, Short checkStatus,
			String userUnit, String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	// 自加， 根据操作人和单位查找报表

	@At("/dataManage/expFirstPass")
	@Ok("jsp:/static/ocean/dataManage/expFirstPassList")
	public ResultVO<ReportVO> queryFirstExportReports(@Param("unitName") String userUnit,
			@Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
			@Param("p") Integer pageNum, HttpSession session, HttpServletRequest request) {

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		// 当前登录用户的id

		String userId = voUser.getId();
		request.setAttribute("userId", userId);
		String userAreaId = voUser.getUserAreaId();

		Short checkStatus = 55;
		String reportTypeNo = null;

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(userAreaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(userAreaId);
		for (Area area : list) {
			areaIds.add(area.getId());
		}
		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}
		// 未同步到外网的
		filter.addRule(new FilterRule(FilterConstant.OR, "reportFlag", "0"));
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		ResultVO<ReportVO> voResultReport = toVoResultReport(reportService.queryReports(filter, page));
		// List<Report> operationResult = voResultReport.getOperationResult();
		// List<Report> reportList=new ArrayList<Report>();
		// for(Report report:operationResult)
		// {
		// if(!reportEIService.isReportIdExist(report.getId()))
		// reportList.add(report);
		// else
		// voResultReport.setTotalCount(voResultReport.getTotalCount()-1);
		// }
		// voResultReport.setOperationResult(reportList);
		return voResultReport;
	}

	@At("/dataManage/expReportPage/?")
	@Ok("jsp:/static/ocean/dataManage/expReportList")
	public ResultVO<ReportVO> queryExportReports(Short checkStatus, @Param("unitName") String userUnit,
			@Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
			@Param("p") Integer pageNum, HttpSession session, HttpServletRequest request) {

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		// 当前登录用户的id

		String userId = voUser.getId();
		request.setAttribute("userId", userId);
		request.setAttribute("checkStatus", checkStatus);
		String userAreaId = voUser.getUserAreaId();

		String reportTypeNo = null;

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(userAreaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(userAreaId);
		for (Area area : list) {
			areaIds.add(area.getId());
		}
		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}

		if (StringUtils.isNotBlank(userUnit)) {

			//			try {
			//				userUnit = new String(userUnit.getBytes("ISO8859-1"), "utf-8");
			//			} catch (UnsupportedEncodingException e) {
			//				// TODO Auto-generated catch block
			//				e.printStackTrace();
			//			}
			request.setAttribute("userUnit", userUnit);
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}
		// 未同步到外网的
		filter.addRule(new FilterRule(FilterConstant.OR, "reportFlag", "0"));
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		ResultVO<ReportVO> voResultReport = toVoResultReport(reportService.queryReports(filter, page));
		// List<Report> operationResult = voResultReport.getOperationResult();
		// List<Report> reportList=new ArrayList<Report>();
		// for(Report report:operationResult)
		// {
		// if(!reportEIService.isReportIdExist(report.getId()))
		// reportList.add(report);
		// else
		// voResultReport.setTotalCount(voResultReport.getTotalCount()-1);
		// }
		// voResultReport.setOperationResult(reportList);

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());

		return voResultReport;
	}

	@At("/dataManage/expReject")
	@Ok("jsp:/static/ocean/dataManage/expRejectList")
	public ResultVO<ReportVO> queryExportRejectReports(@Param("unitName") String userUnit,
			@Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
			@Param("p") Integer pageNum, HttpSession session, HttpServletRequest request) {

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		// 当前登录用户的id

		String userId = voUser.getId();
		request.setAttribute("userId", userId);
		String userAreaId = voUser.getUserAreaId();

		Short checkStatus = 5;
		String reportTypeNo = null;

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(userAreaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(userAreaId);
		for (Area area : list) {
			areaIds.add(area.getId());
		}
		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}
		// 未同步到外网的
		filter.addRule(new FilterRule(FilterConstant.OR, "reportFlag", "0"));
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		ResultVO<ReportVO> voResultReport = toVoResultReport(reportService.queryReports(filter, page));
		// List<Report> operationResult = voResultReport.getOperationResult();
		// List<Report> reportList=new ArrayList<Report>();
		// for(Report report:operationResult)
		// {
		// if(!reportEIService.isReportIdExist(report.getId()))
		// reportList.add(report);
		// else
		// voResultReport.setTotalCount(voResultReport.getTotalCount()-1);
		// }
		// voResultReport.setOperationResult(reportList);
		return voResultReport;
	}

	// 自加， 根据操作人和单位查找报表
	public ResultVO<ReportVO> queryReportsExport(String userId, String userAreaId, Short checkStatus, String userUnit,
			String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(userAreaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(userAreaId);
		for (Area area : list) {
			areaIds.add(area.getId());
		}
		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}
		// 未同步到外网的
		filter.addRule(new FilterRule(FilterConstant.OR, "reportFlag", "0"));
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		ResultVO<ReportVO> voResultReport = toVoResultReport(reportService.queryReports(filter, page));
		// List<Report> operationResult = voResultReport.getOperationResult();
		// List<Report> reportList=new ArrayList<Report>();
		// for(Report report:operationResult)
		// {
		// if(!reportEIService.isReportIdExist(report.getId()))
		// reportList.add(report);
		// else
		// voResultReport.setTotalCount(voResultReport.getTotalCount()-1);
		// }
		// voResultReport.setOperationResult(reportList);
		return voResultReport;
	}

	// 自加， 根据操作人和单位查找报表
	public ResultVO<ReportVO> queryReportsByOperatorAndUnit(String userId, String userAreaId, Short checkStatus,
			String userUnit, String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "operator.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	// 自加， 根据用户地区和企位查找报表
	public ResultVO<ReportVO> queryReportsByAreaAndIndustry(String userId, String userAreaId, Short checkStatus,
			String userUnitIndustry, String reportTypeNo, Date startingReportDate, Date endingReportDate,
			Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (userUnitIndustry != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportUnitIndustry", userUnitIndustry));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportReferenceId", ""));

		// filter.addRule(new FilterRule(FilterConstant.NOT_NULL,
		// "reportUnitIndustry", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	// 自加，查询区域企业报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryEnterpriseReportsByArea(String userAreaId, Short checkStatus, String reportSystem,
			String reportTypeNo, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		} else if (!StringUtils.isNotBlank(reportTypeNo) && StringUtils.isNotBlank(reportSystem)) {
			Filter typeFilter = new Filter();
			StatSystem ss = statSystemService.getStatSystemByName(reportSystem.trim());
			if (ss != null) {
				typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", ss.getId()));
			}

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}

		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportService.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	// 根据用户及代填用户查询报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByUserAndProxy(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (reportProxyId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportProxyId", reportProxyId));
		}

		if (checkStatus != null) {
			if (ReportConstant.FLAG_UNCOMMITTED == checkStatus) {
				filter.addRule(new FilterRule(FilterConstant.ORVALUE, "reportCheckStatus", checkStatus, Short
						.valueOf(ReportConstant.FLAG_PROVINCE_REJECTED)));
			} else {
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
			}
		}

		// 省驳回企业上报

		if (StringUtils.isNotBlank(reportTypeCode)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportTypeCode));
		} else if (!StringUtils.isNotBlank(reportTypeCode) && StringUtils.isNotBlank(reportSystem)) {
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeSystem", reportSystem.trim()));

			cn.com.generaldata.os.paging.Result result = reportService.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}

		// 获取最高版本的报表信息
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", Float.valueOf(reportVersion)));

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportService.queryReports(filter, page));
	}

	//	@At("/data/submitList")
	//	@Ok("jsp:/static/ocean/data/submitList")
	//	// 根据用户及代填用户查询报表
	//	@SuppressWarnings("unchecked")
	//	public ResultVO<ReportVO> queryReportsByParent(@Param("typeId") String reportSystem, @Param("reportTypeId") String reportTypeCode,
	//			@Param("versionId") String reportVersion, @Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
	//			@Param("p") Integer pageNum, @Param("flag") Integer flag, @Param("createYear") String year, HttpServletRequest request, HttpSession session) {
	//
	//		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
	//		// 当前登录用户的id
	//		String reportProxyId = voUser.getId();
	//		request.setAttribute("reportProxyId", reportProxyId);
	//		String areaId = voUser.getUserAreaId();
	//
	//		String userId = null;
	//		Short checkStatus = 1;
	//
	//		request.setAttribute("yearList", yearList);
	//
	//		// 报表制度
	//		List<SystemCodedic> sysList = queryType();
	//		request.setAttribute("sysList", sysList);
	//
	//		// 版本
	//		List<VersionVO> vsList = new ArrayList<VersionVO>();
	//		vsList = this.queryReportVersion(null).getOperationResult();
	//		request.setAttribute("vsList", vsList);
	//
	//		Page page = null;
	//		if (pageNum != null) {
	//			page = new Page(pageNum, 20);
	//		} else {
	//			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
	//		}
	//		return toVoResultReport(reportService.queryReportsByParent(reportProxyId, userId, checkStatus, reportSystem, reportTypeCode, reportVersion,
	//				startingReportDate, endingReportDate, areaId, pageNum, page, year));
	//	}
	//
	//	@At("/data/rejectedList")
	//	@Ok("jsp:/static/ocean/data/rejectedList")
	//	// 根据用户及代填用户查询报表
	//	public ResultVO<ReportVO> queryRejectedReportsByParent(@Param("typeId") String reportSystem, @Param("reportTypeId") String reportTypeCode,
	//			@Param("versionId") String reportVersion, @Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
	//			@Param("p") Integer pageNum, @Param("flag") Integer flag, @Param("createYear") String year, HttpServletRequest request, HttpSession session) {
	//
	//		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
	//		// 当前登录用户的id
	//
	//		String reportProxyId = voUser.getId();
	//		request.setAttribute("reportProxyId", reportProxyId);
	//		String areaId = voUser.getUserAreaId();
	//
	//		String userId = null;
	//		Short checkStatus = 3;
	//
	//		request.setAttribute("yearList", yearList);
	//
	//		// 报表制度
	//		List<SystemCodedic> sysList = queryType();
	//		request.setAttribute("sysList", sysList);
	//
	//		// 版本
	//		List<VersionVO> vsList = new ArrayList<VersionVO>();
	//		vsList = this.queryReportVersion(null).getOperationResult();
	//		request.setAttribute("vsList", vsList);
	//
	//		Page page = null;
	//		if (pageNum != null) {
	//			page = new Page(pageNum, 20);
	//		}
	//		return toVoResultReport(reportService.queryReportsByParent(reportProxyId, userId, checkStatus, reportSystem, reportTypeCode, reportVersion,
	//				startingReportDate, endingReportDate, areaId, pageNum, page, year));
	//	}
	//
	//	@At("/data/passList")
	//	@Ok("jsp:/static/ocean/data/passList")
	//	public ResultVO<ReportVO> queryPassReportsByParent(@Param("typeId") String reportSystem, @Param("reportTypeId") String reportTypeCode,
	//			@Param("versionId") String reportVersion, @Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate,
	//			@Param("p") Integer pageNum, @Param("flag") Integer flag, @Param("createYear") String year, HttpServletRequest request, HttpSession session) {
	//
	//		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
	//		// 当前登录用户的id
	//
	//		String reportProxyId = voUser.getId();
	//		request.setAttribute("reportProxyId", reportProxyId);
	//		String areaId = voUser.getUserAreaId();
	//
	//		String userId = null;
	//		Short checkStatus = 5;
	//
	//		request.setAttribute("yearList", yearList);
	//
	//		// 报表制度
	//		List<SystemCodedic> sysList = queryType();
	//		request.setAttribute("sysList", sysList);
	//
	//		// 版本
	//		List<VersionVO> vsList = new ArrayList<VersionVO>();
	//		vsList = this.queryReportVersion(null).getOperationResult();
	//		request.setAttribute("vsList", vsList);
	//
	//		Page page = null;
	//		if (pageNum != null) {
	//			page = new Page(pageNum, 20);
	//		}
	//		return toVoResultReport(reportService.queryReportsByParent(reportProxyId, userId, checkStatus, reportSystem, reportTypeCode, reportVersion,
	//				startingReportDate, endingReportDate, areaId, pageNum, page, year));
	//	}

	/**
	 * 获取已提交报表清单
	 * @param checkStatus  状态： 1、已提交   3、审核未通过     5、终审通过
	 * */
	@At("/data/report/list/?")
	@Ok("jsp:/static/company/report/list")
	public ResultVO<ReportVO> reportList(Short checkStatus, @Param("reportProxyId") String reportProxyId,
			@Param("typeId") String reportSystem, @Param("reportTypeId") String reportTypeCode,
			@Param("versionId") String reportVersion, @Param("searchDate") Date startingReportDate,
			@Param("endDate") Date endingReportDate, @Param("p") Integer pageNum, @Param("reportNo") String typeNo,
			HttpServletRequest reqeust) {

		UserVO user = (UserVO) reqeust.getSession().getAttribute("user");

		String unitId = user.getUserUnitId();
		String userId = user.getId();
		String userAreaId = user.getUserAreaId();
		reportProxyId = userId;

		//查询当前用户涉及的报表制度
		//reqeust.setAttribute("sysCodeList", queryTypeNew(unitId));
		reqeust.setAttribute("sysCodeList", this.queryType());

		//报表状态
		reqeust.setAttribute("checkStatus", checkStatus);

		//获取频率类型信息
		reqeust.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		if (CommonUtils.isNotBlank(typeNo)) {
			reqeust.setAttribute("typeNo", typeNo);
		}

		Page page = null;
		if (pageNum == null) {
			pageNum = new Integer(1);
		}
		page = new Page(pageNum, 20);

		return toVoResultReport(reportService.queryReportsByParent(reportProxyId, userId, checkStatus, reportSystem,
				reportTypeCode, reportVersion, startingReportDate, endingReportDate, userAreaId, pageNum, page, typeNo));
	}

	@At("/data/changeSys")
	@Ok("json")
	@Filters
	public List<VersionVO> getVersionList(@Param("id") String id) {
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		return this.queryReportVersion(id).getOperationResult();
	}

	// 根据用户及代填用户查询报表
	@At("/data/getReps")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> queryRepsByStAndYear(@Param("versionId") String versionId, @Param("typeId") String typeId) {

		List<ReportTypeVO> list = this.queryReportTypesByParam(versionId, typeId);
		return list;

	}

	// 2014-9-26--cuibaoSelect.mxml
	@At("/monitor/getReps")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> queryRepsByStAndYear2(@Param("year") String year, @Param("typeId") String typeId)
			throws ParseException {
		Date parse = new Date();
		if (!StringUtils.isBlank(year))
			parse = sf.parse(year);
		VersionVO vs = this.queryVersionByYear(parse, typeId);
		if (vs != null) {
			List<ReportTypeVO> list = this.queryReportTypesByParam(String.valueOf(vs.getId()), typeId);
			return list;
		} else {
			return null;
		}

	}

	@At("/data/rejected")
	@Ok("json")
	public String rejectedReportAttachsDisposal(@Param("idStr") String idStr, HttpSession session) {

		String[] idArray = idStr.split(",");
		List<String> list = Arrays.asList(idArray);

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();

		batchChangeStatus(list, userId);

		return "{id:0}";
	}

	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByProxy(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, String areaId, Integer pageNum, String flag, String year, String unitName) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportService.queryReportsByProxy(reportProxyId, userId, checkStatus, reportSystem,
				reportTypeCode, reportVersion, startingReportDate, endingReportDate, areaId, pageNum, page, flag, year,
				unitName));

	}

	public void mutiQuery(String userId, String checkStatus, String reporTypeId, Date startingReportDate,
			Date endingReportDate, String flag) {

	}

	public ResultVO<ReportVO> queryAllReport(String areaId, String unitName, String reportSystem, String reportTypeId,
			String industryId, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum,
			String status, String year) {

		// Page page = null;
		// if (pageNum != null) {
		// page = new Page(pageNum, 20);
		// }
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResultReport(reportService.queryAllReport(areaId, unitName, reportSystem, reportTypeId, industryId,
				reportVersion, startingReportDate, endingReportDate, pageNum, page, status, year));

	}

	public String generalExcel(List<String> ids, String areaId) {
		String[] arrIds = new String[ids.size()];
		ids.toArray(arrIds);

		String excel = reportTmplate.generalExcel(ids, areaId);
		return excel;
	}

	/**
	 * 导出报表.
	 * 
	 * @param idStr
	 *            逗号分隔的报表ID
	 * @return
	 */
	@At("/report/exportReport")
	@Ok("void")
	public void viewUser(@Param("idStr") String idStr, HttpServletResponse response) {

		if (idStr == null || idStr.length() == 0) {
			throw new RuntimeException("参数错误。");
		}

		// 生成Excel
		String[] idArray = idStr.split(",");
		List<String> idList = Arrays.asList(idArray);
		String zipPath = reportTmplate.generalExcel(idList, "");

		// 导出路径
		String filePath = excelDownPath + File.separator + zipPath;
		CommonUtil.downloadFile(filePath, "导出报表.zip", response);
	}

	// 自加,根据reportId查找该列表记录

	public List<ReportVO> queryReportsByReportId(String reportId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (reportId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportReferenceId", reportId));
		}

		return toVoResultReport(reportService.queryReports(filter, null)).getOperationResult();
	}

	@SuppressWarnings("unchecked")
	public void batchChangeStatus(List<String> ids, String operatorId) {

		Short checkStatus = 3;
		String common = null;

		if (checkStatus != null && ids != null && ids.size() > 0) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", arrIds));
			List<cn.com.generaldata.os.pojo.Report> reports = (List<cn.com.generaldata.os.pojo.Report>) reportService
					.queryReports(filter, null).getOperationResult();

			for (cn.com.generaldata.os.pojo.Report report : reports) {
				report.setReportCheckStatus(checkStatus);

				if (common != null) {
					report.setReportCheckComment(common);
				}
				User operator = userService.queryUserById(operatorId);
				report.setOperator(operator);
				// FLAG_PASSED=6:总局审核通过
				// FLAG_PROVINCE_PASSED_UNCOMMITTED=2:省审核通过企业上报未提交总局
				if (checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PASSED).shortValue()
						|| checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_UNCOMMITTED)
								.shortValue()) {
					report.setReportCheckSuccessDate(new Date());
				}
				// 如果是本级海洋局用户提交直接提交上级(内网肯定是海洋局用户填报)或者代填的
				if ((report.getOperator().getId().equals(report.getUser().getId()) || report.getOperator().getId()
						.equals(report.getReportProxyId()))
						&& checkStatus.shortValue() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) {
					report.setReportCheckStatus(Short.valueOf("5"));
				}

				// 改变报表的状态
				reportService.modifyReport(report);

				// webservice调用开始
				ModelSend mo = new ModelSend();
				mo.setObj(report);
				mo.setFlag("5");
				new Thread(mo).start();
				// webservice调用结束

				// 记录历史，并进行留痕操作
				// FLAG_PASSED=6:总局审核通过
				if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PASSED).shortValue()) {
					// markingService.mark4Passing(toMVCReport(report,
					// getReportDetails(report.getId())));
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					//
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(),
							report.getReportCheckComment(), report.getReportCheckResult(), new Date()));
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_REJECTED).shortValue()) { // FLAG_REJECTED
					// = 7;
					// 总局驳回
					// markingService.mark4Rejecting(toMVCReport(report,
					// getReportDetails(report.getId())));
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(),
							report.getReportCheckComment(), report.getReportCheckResult(), new Date()));
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PRE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_UNCOMMITTED
											// =
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// 2; 省审核通过企业上报未提交总局
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(),
							report.getReportCheckComment(), "初审通过", new Date()));
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_REJECTED)
						.shortValue()) { // FLAG_PROVINCE_REJECTED
					// =
					// 3;
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// //省驳回企业上报
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(), null, "驳回报表上报", new Date()));
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) { // FLAG_COMMITTED
					// = 1;
					// //
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// 企业提交省区未审核
					// markingService.mark4Submitting(toMVCReport(report,
					// getReportDetails(report.getId())));
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(), null, "提交报表,待审核", new Date()));
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_COMMITTED
											// =
											// 5;
					reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// //省审核通过企业上报并提交总局
					historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null,
							report.getOperator(), report, report.getReportCheckStatus(),
							report.getReportCheckComment(), "终审通过", new Date()));
				}
			}
		}
	}

	// 报表删除
	@At("/report/delete")
	@Ok("json")
	public Map<String, String> deleteReport(@Param("ids") String ids, HttpServletRequest request, HttpSession session) {
		List<String> listIds = new ArrayList<String>();
		String[] id = ids.split(",");
		for (String addId : id) {
			if (addId.trim().length() == 0) {
				continue;
			}
			listIds.add(addId);
		}
		removeReports(listIds);
		return CommonUtil.createOKMsg("删除成功");
	}

	public void removeReports(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			reportService.removeReports(arrIds);
		}
	}

	// 新建报表类别

	public String createReportType(String reportName) {

		// reportService.queryReportTypes(filter, null)
		//
		// String reportid = reportService.createReportType(reportType);

		return "";
	}

	public ReportTypeVO queryReportTypeById(String id) {
		cn.com.generaldata.os.newpojo.ReportType typeById = reportTypeService.getReportTypeById(id);
		List<SystemCodedic> queryType = queryType();
		return toVoReportType(typeById, queryType);
	}

	public List<ReportTypeVO> queryReportTypes() {
		String hql = "from ReportType as rt order by rt.statSystem,rt.sortNo,rt.subSortNo";
		cn.com.generaldata.os.paging.Result hqlParam = reportService.queryReportTypeByHql(hql, null, null);
		return toVoListReportType(hqlParam);
	}

	public List<String> queryReportTypesUnit(String unitId) {

		return reportService.queryReportTypesUnit(unitId);
	}

	public List<ReportTypeVO> queryReportTypesByParam(String version, String type) {
		String hql = "from ReportType as rt where rt.versionId=:version and statSystem=:statSystem order by rt.statSystem,rt.sortNo,rt.subSortNo";
		HashMap map = new HashMap();
		map.put("version", Integer.valueOf(version));
		map.put("statSystem", Integer.valueOf(type));
		cn.com.generaldata.os.paging.Result hqlParam = reportService.queryReportTypeByHql(hql, map, null);
		return toVoListReportType(hqlParam);
	}

	public List<ReportTypeVO> queryReportTypesSum(String version, String type) {

		List<SummaryReportType> hqlParam = reportService.queryReportTypeNew(version, type);
		return toVoListReportType(hqlParam);
	}

	public List<ReportTypeVO> queryReportTypesByUserId(String userId) {
		if (userId != null) {
			User user = userService.queryUserById(userId);
			if (user.getUserIndustrys() != null) {
				Set<UserIndustry> industrys = user.getUserIndustrys();
				List<SystemCodedic> queryType = queryType();
				List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
				for (UserIndustry industry : industrys) {
					Industry industry2 = industry.getIndustry();
					List<cn.com.generaldata.os.newpojo.ReportType> queryReportTypeByIndustryId = reportService
							.queryReportTypeByIndustryId(industry2.getId());

					for (cn.com.generaldata.os.newpojo.ReportType dustryReport : queryReportTypeByIndustryId) {
						ReportTypeVO voReportType = toVoReportType(dustryReport, queryType);
						if (voReportType != null && voReportType.getTypeCode() != null) {
							reportTypes.add(voReportType);
						}
					}
				}

				Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {
					@Override
					public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
						return rt1.getTypeCode().compareTo(rt2.getTypeCode());
					}
				});
				return reportTypes;
			}

		}
		return new ArrayList<ReportTypeVO>();
	}

	// 查询所选用户尚未提交的报表类型,自加(省区局使用)
	public ResultVO<ReportTypeVO> queryUncommittedReportTypesByUserId(String eUserLoginname, short checkStatus,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		Filter reportFilter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("typeNo");

		Filter userFilter = new Filter();

		if (StringUtils.isNotBlank(eUserLoginname)) {
			userFilter.addRule(new FilterRule(FilterConstant.EQUAL, "userLoginname", eUserLoginname));
			// System.out.println(eUserLoginname);
		}

		cn.com.generaldata.os.paging.Result uResult = userService.queryUsers(userFilter, null);

		if (uResult.getOperationResult().size() > 0) {
			User eUser = (User) uResult.getOperationResult().get(0);
			reportFilter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", eUser.getId()));
			List<cn.com.generaldata.os.newpojo.ReportType> pReportTypes = new ArrayList<cn.com.generaldata.os.newpojo.ReportType>();
			if (eUser.getUserIndustrys() != null) {
				Set<UserIndustry> industrys = eUser.getUserIndustrys();
				for (UserIndustry industry : industrys) {
					pReportTypes.addAll(reportService.queryReportTypeByIndustryId(industry.getIndustry().getId()));
				}
			}
			String[] ids = new String[pReportTypes.size()];
			for (int i = 0; i < pReportTypes.size(); i++) {
				ids[i] = pReportTypes.get(i).getId();
			}
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", ids));
		}

		reportFilter.addRule(new FilterRule(FilterConstant.GT, "reportCheckStatus", checkStatus));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			reportFilter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			reportFilter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		cn.com.generaldata.os.paging.Result result = reportService.queryReports(reportFilter, null);

		List<cn.com.generaldata.os.pojo.Report> pReports = (List<cn.com.generaldata.os.pojo.Report>) result
				.getOperationResult();

		Set set = new HashSet();
		if (result.getOperationResult().size() > 0) {
			for (int i = 0; i < pReports.size(); i++) {
				set.add(pReports.get(i).getReportTypeId());
			}
			Object[] typeCodes = new Object[set.size()];
			set.toArray(typeCodes);
			filter.addRule(new FilterRule(FilterConstant.UNCOLLECTION, "id", typeCodes));
		}

		return toVoResultReportType(reportService.queryReportTypes(filter, page));
	}

	// 查询所选用户尚未提交的报表类型,自加(总局使用)
	public ResultVO<ReportTypeVO> queryUncommittedReportTypesByOperatorId(String eUserLoginname, short checkStatus,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {
		Filter filter = new Filter();
		Filter reportFilter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("typeNo");

		Filter userFilter = new Filter();

		if (StringUtils.isNotBlank(eUserLoginname)) {
			userFilter.addRule(new FilterRule(FilterConstant.EQUAL, "userLoginname", eUserLoginname));
			// System.out.println(eUserLoginname);
		}

		cn.com.generaldata.os.paging.Result uResult = userService.queryUsers(userFilter, null);

		if (uResult.getOperationResult().size() > 0) {
			User eUser = (User) uResult.getOperationResult().get(0);
			reportFilter.addRule(new FilterRule(FilterConstant.EQUAL, "operator.id", eUser.getId()));
		}

		reportFilter.addRule(new FilterRule(FilterConstant.GT, "reportCheckStatus", checkStatus));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			reportFilter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			reportFilter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		cn.com.generaldata.os.paging.Result result = reportService.queryReports(reportFilter, null);

		List<cn.com.generaldata.os.pojo.Report> pReports = (List<cn.com.generaldata.os.pojo.Report>) result
				.getOperationResult();

		Set set = new HashSet();
		if (result.getOperationResult().size() > 0) {
			for (int i = 0; i < pReports.size(); i++) {
				set.add(pReports.get(i).getReportTypeId());
			}
			Object[] typeCodes = new Object[set.size()];
			set.toArray(typeCodes);
			filter.addRule(new FilterRule(FilterConstant.UNCOLLECTION, "id", typeCodes));
		}

		return toVoResultReportType(reportService.queryReportTypes(filter, page));
	}

	public List<ReportTypeVO> queryReportTypesByIndustryId(String industryId) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();

		if (StringUtils.isNotBlank(industryId)) {
			List<SystemCodedic> queryType = queryType();
			for (cn.com.generaldata.os.newpojo.ReportType pReportType : reportService
					.queryReportTypeByIndustryId(industryId)) {
				ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
				if (voReportType != null && voReportType.getTypeCode() != null) {
					reportTypes.add(voReportType);
				}
			}
		}

		Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {
			@Override
			public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
				return rt1.getTypeCode().compareTo(rt2.getTypeCode());
			}
		});

		return reportTypes;
	}

	public List<ReportTypeVO> queryReportTypesByPara(String industryId, String code, String version) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();

		if (StringUtils.isNotBlank(industryId)) {
			List<SystemCodedic> queryType = queryType();
			List<cn.com.generaldata.os.newpojo.ReportType> queryReportTypeByIndustryId = reportService
					.queryReportTypeByIndustryId(industryId);
			for (cn.com.generaldata.os.newpojo.ReportType pReportType : queryReportTypeByIndustryId) {
				ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
				if (voReportType != null && voReportType.getTypeCode() != null) {
					if (code != null && !"".equals(code)) {
						if (code.equals(voReportType.getTypeCode())) {
							if (version != null && !"".equals(version)) {
								if (version.equals(voReportType.getVersionId())) {
									reportTypes.add(voReportType);
								}
							} else {
								reportTypes.add(voReportType);
							}
						}
					} else {
						if (version != null && !"".equals(version)) {
							if (version.equals(voReportType.getVersionId())) {
								reportTypes.add(voReportType);
							}
						} else {
							reportTypes.add(voReportType);
						}
					}
				}
			}
		}

		Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {
			@Override
			public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
				return rt1.getTypeCode().compareTo(rt2.getTypeCode());
			}
		});
		return reportTypes;
	}

	public String exportPassedReports(String userId, String areaId) {
		try {
			String path = exporter.export(userId, areaId);
			String webRootPath = new ClassPathResource("/").getFile().getParentFile().getParentFile().getAbsolutePath();
			String pathZip = webRootPath + File.separator + "export.zip";
			// System.out.println("pathZip: " + pathZip);
			// 增加压缩工具
			ZipCompressor zip = new ZipCompressor(pathZip);
			zip.compress(path);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		url = "http://localhost:8080/jsme-das-lan/export.zip";

		// urlList.add(url);
		// return urlList;
		return url;
	}

	public boolean importReports() {
		String importRootPath = EXPORT_ROOT_DIR + File.separator + EXPORT_ROOT_DIR_1 + File.separator;
		String backupRootPath = EXPORT_ROOT_DIR + File.separator + EXPORT_FILE_BACKUP + File.separator;

		List<cn.com.generaldata.os.pojo.mvc.Report> mvcReports;
		try {
			mvcReports = Importer.importReports(importRootPath, backupRootPath);
			for (int i = 0; i < mvcReports.size(); i++) {
				reportService.createMVCReport((mvcReports.get(i)));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return true;
	}

	@At("/data/view")
	@Ok("jsp:/static/ocean/data/reportHistory")
	public void queryHistory(@Param("id") String reportId, HttpServletRequest request) {
		List<ReportHistoryVO> history = showHistory(reportId);
		request.setAttribute("history", history);

	}

	public List<ReportHistoryVO> showHistory(String reportId) {
		return toVoReportHistory(historyService.showHistory(reportId));
	}

	public List<ReportMarkingVO> showReportMarking(String reportId) {
		return toVoReportMarking(markingService.showMarking(reportId));
	}

	public void setExporter(Exporter exporter) {
		this.exporter = exporter;
	}

	private ReportVO toVoReport(cn.com.generaldata.os.pojo.Report pReport) {
		if (pReport != null) {
			String userId = pReport.getUser() == null ? null : pReport.getUser().getId();
			String operatorId = pReport.getOperator() == null ? null : pReport.getOperator().getId();
			String operatorName = null;
			String areaId = pReport.getArea() == null ? null : pReport.getArea().getId();
			User operator = pReport.getOperator();
			if (StringUtils.isBlank(pReport.getReportTimetype())) {
				pReport.setReportTimetype("");
			}
			if (StringUtils.isBlank(pReport.getReportUnitIndustry())) {
				pReport.setReportUnitIndustry("");
			}
			if (StringUtils.isBlank(pReport.getReportReferenceId())) {
				pReport.setReportReferenceId("");
			}
			// if (operator != null)
			// pReport.setReportUnit(operator.getUserUnit().getUnitName());
			// else
			// pReport.setReportRemark(pReport.getReportUnit());
			return new ReportVO(pReport.getId(), pReport.getReportReferenceId(), userId, operatorId, operatorName,
					areaId, pReport.getReportType(), pReport.getReportTypeCode(), pReport.getReportName(),
					pReport.getReportRegionName(), pReport.getReportRegionOcean(), pReport.getReportCityName(),
					pReport.getReportDepartmentName(), pReport.getReportRegionCode(), pReport.getReportUnit(),
					pReport.getReportUnitIndustry(), pReport.getReportInstitutionName(),
					pReport.getReportInstitutionCode(), pReport.getReportDomainName(), pReport.getReportDomainCode(),
					pReport.getReportYear(), pReport.getReportQuarter(), pReport.getReportNo(),
					pReport.getReportAdmin(), pReport.getReportApproveAdmin(), pReport.getReportApproveNo(),
					pReport.getReportExpireDate(), pReport.getReportMeasureUnit(), pReport.getReportUnitAdmin(),
					pReport.getReportStatAdmin(), pReport.getReportFillAdmin(), pReport.getReportDate(),
					pReport.getReportCreateTime(), pReport.getReportLastEditTime(), pReport.getReportCheckStatus(),
					pReport.getReportCheckComment(), pReport.getReportCheckSuccessDate(), pReport.getReportOrigin(),
					pReport.getReportSupplyOrigin(), pReport.getReportDesc(), pReport.getReportCheckResult(),
					pReport.getReportRemark(), pReport.getReportFlag(), pReport.getReportProxyId(),
					pReport.getReportTimetype(), pReport.getReportMonth(), pReport.getReportYearTime(),
					pReport.getReportTypeId(), pReport.getReportEdition(), pReport.getReportVersion(),
					pReport.getUnitId(), pReport.getMonth(), pReport.getQuarter(), pReport.getUpdateTime());

		}
		return null;
	}

	private VersionVO toVoVersion(ReportVersion pVersion) {
		if (pVersion != null) {
			return new VersionVO(pVersion.getId().toString(), pVersion.getVersionNumber(), pVersion.getVersionName(),
					pVersion.getCreateTime(), pVersion.getStatSystem());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportVO> toVoResultReport(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportVO> result = new ResultVO<ReportVO>();

		List<ReportVO> reports = new ArrayList<ReportVO>();
		for (cn.com.generaldata.os.pojo.Report pReport : (List<cn.com.generaldata.os.pojo.Report>) pResult
				.getOperationResult()) {
			ReportVO voReport = toVoReport(pReport);
			if (voReport != null) {
				reports.add(voReport);
			}
		}
		result.setOperationResult(reports);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<VersionVO> toVoResultVersion(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<VersionVO> result = new ResultVO<VersionVO>();

		List<VersionVO> versions = new ArrayList<VersionVO>();
		for (ReportVersion pVersion : (List<ReportVersion>) pResult.getOperationResult()) {
			VersionVO voVersion = toVoVersion(pVersion);
			if (voVersion != null) {
				versions.add(voVersion);
			}
		}
		result.setOperationResult(versions);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportTypeVO> toVoResultReportType(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportTypeVO> result = new ResultVO<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		for (cn.com.generaldata.os.newpojo.ReportType pReportType : (List<cn.com.generaldata.os.newpojo.ReportType>) pResult
				.getOperationResult()) {
			ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		result.setOperationResult(reportTypes);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	private ReportTypeVO toVoReportType(cn.com.generaldata.os.newpojo.ReportType pReportType,
			List<SystemCodedic> queryType) {
		if (pReportType != null) {
			String type = "";
			for (SystemCodedic sc : queryType) {
				if (sc.getCode().equals(pReportType.getStatSystem().toString())) {
					type = sc.getCodeName();
					break;
				}
			}
			String name = pReportType.getTypeName();
			if (pReportType.getTypeNo() != null) {
				name = pReportType.getTypeNo() + "-" + pReportType.getTypeName();
			}
			return new ReportTypeVO(pReportType.getId(), name, pReportType.getTypeNo(), pReportType.getStatSystem()
					.toString(), pReportType.getTypeReportAdmin().toString(), pReportType.getTypeApproveAdmin()
					.toString(), pReportType.getTypeApproveNo(), pReportType.getTypeExpireDate(),
					pReportType.getTypeMeasureUnit(), pReportType.getTypeLastTime() == null ? 0 : pReportType
							.getTypeLastTime().shortValue(), pReportType.getTypeYearTime(), pReportType.getTypeTime(),
					type, pReportType.getVersionId().toString(), pReportType.getId());
		}
		return null;
	}

	private ReportTypeVO toVoReportType(SummaryReportType pReportType, List<SystemCodedic> queryType) {
		if (pReportType != null) {
			String type = "";
			for (SystemCodedic sc : queryType) {
				if (sc.getCode().equals(pReportType.getStatSystem().toString())) {
					type = sc.getCodeName();
					break;
				}
			}
			String name = pReportType.getTypeName();
			if (pReportType.getTypeNo() != null) {
				name = pReportType.getTypeNo() + "-" + pReportType.getTypeName();
			}
			return new ReportTypeVO(pReportType.getReportTypeId(), name, pReportType.getTypeNo(), pReportType
					.getStatSystem().toString(), pReportType.getTypeReportAdmin().toString(), pReportType
					.getTypeApproveAdmin().toString(), pReportType.getTypeApproveNo(), pReportType.getTypeExpireDate(),
					pReportType.getTypeMeasureUnit(), pReportType.getTypeLastTime() == null ? 0 : pReportType
							.getTypeLastTime().shortValue(), pReportType.getTypeYearTime(), pReportType.getTypeTime(),
					type, pReportType.getVersionId().toString(), pReportType.getId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private List<ReportTypeVO> toVoListReportType(List<SummaryReportType> pResult) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		for (SummaryReportType srt : pResult) {
			ReportTypeVO voReportType = toVoReportType(srt, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		return reportTypes;
	}

	@SuppressWarnings("unchecked")
	private List<ReportTypeVO> toVoListReportType(cn.com.generaldata.os.paging.Result pResult) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		for (cn.com.generaldata.os.newpojo.ReportType pReportType : (List<cn.com.generaldata.os.newpojo.ReportType>) pResult
				.getOperationResult()) {
			ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		return reportTypes;
	}

	public boolean checkReportViewStatus(String userId, String reportId) {
		if (null == userId || userId.trim().length() == 0) {
			return false;
		}

		if (null == reportId || reportId.trim().length() == 0) {
			return false;
		}

		User user = userService.queryUserById(userId);
		if (null == user) {
			return false;
		}

		cn.com.generaldata.os.pojo.Report dReport = reportService.queryReportById(reportId);
		if (null == dReport) {
			return false;
		}
		ReportVO report = toVoReport(dReport);

		boolean result = true;
		if ("Enterprise".equals(user.getRole().getRoleDesc())) {
			if (ReportConstant.FLAG_COMMITTED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_PASSED == report.getReportCheckStatus()) {
				result = false;
			}
		} else if ("Ocean".equals(user.getRole().getRoleDesc())) {
			if (ReportConstant.FLAG_UNCOMMITTED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_PASSED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_REJECTED == report.getReportCheckStatus()) {
				result = false;
			}
		} else {
			result = false;
		}
		return result;
	}

	private List<ReportHistoryVO> toVoReportHistory(List<cn.com.generaldata.os.pojo.ReportHistory> pHistories) {
		List<ReportHistoryVO> result = new ArrayList<ReportHistoryVO>();
		for (cn.com.generaldata.os.pojo.ReportHistory pHistory : pHistories) {
			ReportHistoryVO reportHistory = new ReportHistoryVO(pHistory.getId(), pHistory.getOperator().getId(),
					pHistory.getOperator().getUserLoginname(), pHistory.getOperator().getUserUnit().getUnitName(),
					pHistory.getReport().getId(), pHistory.getReportStatus(), pHistory.getReportCheckComment(),
					pHistory.getReportCheckResult(), pHistory.getHistoryDate());
			reportHistory.setReportCheckResult(pHistory.getOperator().getUserUnit().getUnitName()
					+ pHistory.getReportCheckResult() == null ? "" : pHistory.getReportCheckResult());
			result.add(reportHistory);
		}
		return result;
	}

	// 自加
	private List<ReportMarkingVO> toVoReportMarking(List<cn.com.generaldata.os.pojo.ReportMarking> pReportMarkings) {
		List<ReportMarkingVO> result = new ArrayList<ReportMarkingVO>();
		for (cn.com.generaldata.os.pojo.ReportMarking pReportMarking : pReportMarkings) {
			result.add(new ReportMarkingVO(pReportMarking.getId(), pReportMarking.getReport().getId(), pReportMarking
					.getOperator().getId(), pReportMarking.getOperator().getUserLoginname(), pReportMarking
					.getReportStatus(), pReportMarking.getMarkingDate(), pReportMarking.getMarkingContent()));
		}
		return result;
	}

	private cn.com.generaldata.os.pojo.mvc.Report toMVCReport(cn.com.generaldata.os.pojo.Report report,
			List<ReportDetail> reportDetails) {
		List<Row> rows = new ArrayList<Row>();
		for (ReportDetail reportDetail : reportDetails) {
			Row row = BeanMapper.map(reportDetail, Row.class);
			row.setRowId(reportDetail.getId());
			rows.add(row);
		}

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		return new cn.com.generaldata.os.pojo.mvc.Report(String.valueOf(report.getId()), String.valueOf(report
				.getReportReferenceId()), report.getReportType(), report.getReportTypeCode(), String.valueOf(report
				.getUser().getId()), report.getReportRegionName(), report.getReportRegionOcean(),
				report.getReportCityName(), report.getReportDepartmentName(), report.getReportRegionCode(),
				report.getReportUnit(), report.getReportUnitIndustry(), report.getReportUnitIndustryId(),
				report.getReportInstitutionName(), report.getReportInstitutionCode(), report.getReportDomainName(),
				report.getReportDomainCode(), report.getReportYear(), report.getReportQuarter(), report.getReportNo(),
				report.getReportAdmin(), report.getReportApproveAdmin(), report.getReportApproveNo(),
				report.getReportExpireDate(), report.getReportMeasureUnit(), report.getReportUnitAdmin(),
				report.getReportStatAdmin(), report.getReportFillAdmin(), formatter.format(report.getReportDate()),
				report.getReportOrigin(), report.getReportSupplyOrigin(), report.getReportDesc(),
				report.getReportCreateTime(), report.getReportLastEditTime(), String.valueOf(report.getOperator()
						.getId()), String.valueOf(report.getArea().getId()), Byte.valueOf(String.valueOf(report
						.getReportCheckStatus())), report.getReportCheckComment(), report.getReportCheckResult(),
				report.getReportCheckSuccessDate(), report.getReportRemark(), report.getReportFlag(),
				report.getReportProxyId(), rows, report.getReportTimetype(), report.getReportMonth(),
				report.getReportYearTime(), report.getReportVersion(), report.getReportTypeId(),
				report.getReportEdition(), report.getSelfSet1(), report.getSelfSet2(), report.getSelfSet3(),
				report.getSelfSet4(), report.getSelfSet5(), report.getQuarter(), report.getMonth(), report.getUnitId(),
				report.getUpdateTime());
	}

	@SuppressWarnings("unchecked")
	private List<ReportDetail> getReportDetails(String reportId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("rowIndex");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "report.id", reportId));
		return (List<ReportDetail>) reportService.queryReportDetails(filter, null).getOperationResult();
	}

	// 导出所有报表模板
	@At("/dataManage/expReportModel")
	@Ok("json")
	public Boolean exportReportType() {
		return reportEIService.exportReportType();
	}

	// 将业务库的终审通过或驳回报表导到导出库

	@At("/dataManage/expReport/?")
	@Ok("json")
	public String exportEIReport(Short checkStatus, @Param("searchDate") Date startingReportDate,
			@Param("endDate") Date endingReportDate, @Param("p") Integer pageNum, @Param("unitName") String unitName,
			HttpServletRequest request, HttpSession session) {

		// 所有需要导出的报表

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		// 当前登录用户的id

		String reportProxyId = voUser.getId();
		request.setAttribute("reportProxyId", reportProxyId);
		String userId = voUser.getUserAreaId();

		String reportSystem = null;
		String reportTypeCode = null;
		String reportVersion = null;

		ResultVO<ReportVO> export = queryReportsExport(reportProxyId, userId, checkStatus, unitName, reportTypeCode,
				startingReportDate, endingReportDate, null);

		if (export != null) {
			List<ReportVO> result = export.getOperationResult();
			Set<String> ridSet = new HashSet<String>();
			// String[] rids = new String[result.size()];
			for (int i = 0; i < result.size(); i++) {
				ridSet.add(result.get(i).getId());
				// rids[i] = ;parReport.toArray(new String[] {})
			}
			if (!ridSet.isEmpty()) {
				reportEIService.exportEIReport(ridSet);

			}
		}
		return "导出成功。";
	}

	//	@At("/dataManage/downloadFirstPass")
	//	@Ok("jsp:/static/ocean/dataManage/downloadInfoOk")
	//	public Boolean exportFirstEIReport(@Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate, @Param("p") Integer pageNum,
	//			@Param("unitName") String unitName, HttpServletRequest request, HttpSession session) {
	//		// 所有需要导出的报表
	//
	//		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
	//		// 当前登录用户的id
	//
	//		String reportProxyId = voUser.getId();
	//		request.setAttribute("reportProxyId", reportProxyId);
	//		String userId = voUser.getUserAreaId();
	//
	//		Short checkStatus = 55;
	//		String reportSystem = null;
	//		String reportTypeCode = null;
	//		String reportVersion = null;
	//
	//		ResultVO<ReportVO> export = queryReportsExport(reportProxyId, userId, checkStatus, unitName, reportTypeCode, startingReportDate, endingReportDate, null);
	//		if (export != null) {
	//			List<ReportVO> result = export.getOperationResult();
	//			Set<String> ridSet = new HashSet<String>();
	//			// String[] rids = new String[result.size()];
	//			for (int i = 0; i < result.size(); i++) {
	//				ridSet.add(result.get(i).getId());
	//				// rids[i] = ;parReport.toArray(new String[] {})
	//			}
	//			if (!ridSet.isEmpty()) {
	//				reportEIService.exportEIReport(ridSet);
	//
	//			}
	//		}
	//		request.setAttribute("msg", "导出成功。");
	//		return true;
	//	}
	//
	//	@At("/dataManage/downloadReject")
	//	@Ok("jsp:/static/ocean/dataManage/downloadInfoOk")
	//	public Boolean exportRejectEIReport(@Param("searchDate") Date startingReportDate, @Param("endDate") Date endingReportDate, @Param("p") Integer pageNum,
	//			@Param("unitName") String unitName, HttpServletRequest request, HttpSession session) {
	//		// 所有需要导出的报表
	//
	//		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
	//		// 当前登录用户的id
	//
	//		String reportProxyId = voUser.getId();
	//		request.setAttribute("reportProxyId", reportProxyId);
	//		String userId = voUser.getUserAreaId();
	//
	//		Short checkStatus = 55;
	//		String reportSystem = null;
	//		String reportTypeCode = null;
	//		String reportVersion = null;
	//
	//		ResultVO<ReportVO> export = queryReportsExport(reportProxyId, userId, checkStatus, unitName, reportTypeCode, startingReportDate, endingReportDate, null);
	//		if (export != null) {
	//			List<ReportVO> result = export.getOperationResult();
	//			Set<String> ridSet = new HashSet<String>();
	//			// String[] rids = new String[result.size()];
	//			for (int i = 0; i < result.size(); i++) {
	//				ridSet.add(result.get(i).getId());
	//				// rids[i] = ;parReport.toArray(new String[] {})
	//			}
	//			if (!ridSet.isEmpty()) {
	//				reportEIService.exportEIReport(ridSet);
	//
	//			}
	//		}
	//		request.setAttribute("msg", "导出成功。");
	//		return true;
	//	}

	/**
	 * 将业务库的已更新用户导入到导出库.
	 * 
	 * @param idStr
	 *            用户ID的字符串，逗号分隔
	 * @return
	 */
	@At("/report/exportUser")
	@Ok("json")
	public Map<String, String> exportUser(@Param("idStr") String idStr) {

		boolean result = false;
		if (idStr != null && idStr.length() > 0) {
			result = reportEIService.exportUser(idStr.split(","));
		}
		if (result) {
			return CommonUtil.createOKMsg("导出成功。");
		} else {
			return CommonUtil.createNGMsg("导出失败。");
		}
	}

	/**
	 * 更改用户导出完成状态（把flag置1了）.
	 * 
	 * @param idStr
	 *            用户ID的字符串，逗号分隔
	 * @return
	 */
	@At("/report/exportOverUser")
	@Ok("json")
	public Map<String, String> exportOverUser(@Param("idStr") String idStr) {

		boolean result = false;
		if (idStr != null && idStr.length() > 0) {
			result = reportEIService.exportOverUser(idStr.split(","));
		}
		if (result) {
			return CommonUtil.createOKMsg("设置成功。");
		} else {
			return CommonUtil.createNGMsg("设置成功。");
		}
	}

	/**
	 * 将导出入库导入到业务库的已上报报表.
	 * 
	 * @return
	 */
	@At("/report/importEIReport")
	@Ok("json")
	public Map<String, String> importEIReport(HttpSession session) {

		// 导入
		List<ReportVO> reportList = reportEIService.importEIReport();

		// 放到session里，以备后面分页查询
		// session.setAttribute("importReportList", reportList);

		// 返回JSON，客户端启动查询
		return CommonUtil.createOKMsg("执行完毕。");
	}

	/**
	 * 查询已导入的报表，带分页.
	 * 
	 * @return
	 */
	@At("/report/queryImportEIReport")
	@Ok("jsp:/static/ocean/dataManage/importData")
	public ResultVO<ReportVO> queryImportEIReport(@Param("p") Integer pageNum, HttpServletRequest request,
			HttpSession session) {
		return new ResultVO<ReportVO>();
	}

	// 自动清除导入库的数据
	public Boolean cleanEIReport() {
		return reportEIService.cleanEIReport();
	}

	// 获取已经激活的所有的版本信息
	@At("/report/queryReportVersion/?")
	@Ok("json")
	public ResultVO<VersionVO> queryReportVersion(String code) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("endDate");
		if (code == null) {
			code = "1";
		}
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", Integer.valueOf(code)));
		return toVoResultVersion(reportService.queryReportVersion(filter, null));
	}

	// 按年份查询版本

	public VersionVO queryVersionByYear(Date date, String type) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		filter.addRule(new FilterRule(FilterConstant.LE, "startDate", date));
		filter.addRule(new FilterRule(FilterConstant.GE, "endDate", date));
		if (type == null) {
			type = "1";
		}
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", Integer.valueOf(type)));
		cn.com.generaldata.os.paging.Result reportVersion = reportService.queryReportVersion(filter, null);
		if (reportVersion != null && reportVersion.getTotalCount() > 0) {
			List<ReportVersion> operationResult = (List<ReportVersion>) reportVersion.getOperationResult();
			ReportVersion version = operationResult.get(0);
			return toVoVersion(version);
		}
		return null;
	}

	// 查看当前报表制度是否存在

	public VersionVO isVersionSystem(String vSystem) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		if (StringUtils.isNotBlank(vSystem)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "versionName", vSystem));
		}

		return this.toVoVersion(reportService.getVersion(filter, null));
	}

	// 获取最高版本的报表信息

	public String queryReportMaxVersion() {
		Filter versionFilter = new Filter();
		versionFilter.setOrder(FilterConstant.DESC);
		versionFilter.setSortBy("versionNumber");
		String maxVersion = reportService.queryReportMaxVersion(versionFilter, null);
		return String.valueOf(maxVersion);
	}

	public List<ReportPerformVO> reportAccount(String areaId, String timeType, String type) {
		return reportService.reportAccount(areaId, timeType, type);
	}

	// 2014-9-11
	@At("/monitor/alert")
	@Ok("jsp:/static/ocean/monitor/repforfill")
	public List<ReportVO> reportAlert(HttpSession session, HttpServletRequest request) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		List<SystemCodedic> type = queryType();
		List<ReportVO> reportList = new ArrayList<ReportVO>();

		for (SystemCodedic sc : type) {
			reportList.addAll(reportAllQuery(voUser.getId(), sc.getCode(), new Date()));
		}

		return reportList;
	}

	@At("/main")
	public void main(HttpServletRequest req, HttpServletResponse res) {
		// 保存到session
		UserVO voUser = (UserVO) req.getSession().getAttribute("user");
		try {
			// 根据角色ID处理
			String roleId = voUser.getRoleId();
			if (roleId.equals("1")) {
				// 系统管理员				
				res.sendRedirect(req.getContextPath() + "/static/admin/main.jsp");

			} else if (roleId.equals("3") || roleId.equals("5")) {
				// 企业用户，涉海部分禁止内网
				res.sendRedirect(req.getContextPath() + "/static/company/main.jsp");
			} else if (roleId.equals("4")) {
				// 省区局用户，或者叫海洋局用户
				res.sendRedirect(req.getContextPath() + "/mainTitle/main");
			} else if (roleId.equals("6")) {
				// 普通浏览用户，不可编辑
				res.sendRedirect(req.getContextPath() + "/static/browsers/main.jsp");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@At("/mainTitle/main")
	@Ok("jsp:/static/ocean/mainTitle/mainTitle")
	public void mainTitle(HttpSession session, HttpServletRequest request, @Param("p") Integer pageNum) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		// 获取消息管理
		ResultVO<Pm> pm = pmWS.getPmList(session, request, pageNum);
		List<Pm> pmList = pm.getOperationResult();
		// 获取待填报
		List<ReportVO> reportList = reportAlert(session, request);
		//		List<BillboardIndustryVO> billboardIndustryList = 
		// 获取催报
		ResultVO<BillboardVO> billboardsInEnterprise = billWS.queryBillboardsInEnterprise(session, request);
		request.setAttribute("pmList", pmList);
		request.setAttribute("reportList", reportList);
		request.setAttribute("billboardIndustryList",
				billboardsInEnterprise == null ? null : billboardsInEnterprise.getOperationResult());
	}

	// 2014-9-25
	@At("/monitor/unrepcom")
	@Ok("jsp:/static/ocean/monitor/unrepcompany")
	public List<cn.com.generaldata.os.vo.UnitVO> queryNoUnits(@Param("roleId") String roleId,
			@Param("createYear") Date createYear, @Param("sysId") String sysId, @Param("repId") String repId,
			HttpServletRequest request, HttpSession session) {

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String unitId = voUser.getUserUnitId();
		// String areaId = "320900000000";
		// 单位类型是roleWs的queryAllRoles所有用户角色
		List<Role> roleList = new ArrayList<Role>();
		roleList = roleService.queryAllRoles();
		Role rol = new Role();
		rol.setId("2");
		rol.setRoleName("涉海企业用户");
		roleList.add(rol);
		request.setAttribute("roleList", roleList);
		if (createYear == null) {
			createYear = new Date();
			request.setAttribute("createYear", createYear);
		}
		//
		List<ReportTypeVO> repList = new ArrayList<ReportTypeVO>();
		if (createYear != null && sysId != null) {
			VersionVO vs = this.queryVersionByYear(createYear, sysId);
			if (vs != null) {
				repList = this.queryReportTypesByParam(String.valueOf(vs.getId()), sysId);
			}
			request.setAttribute("repList", repList);
		}
		// 年份是versionWS的getReportVersionYearRange查出所有版本的起始年到终止年。
		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = yearRange.getEndYear();
		List<Integer> yearList = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			yearList.add(i);
		}
		request.setAttribute("yearList", yearList);
		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("sysList", sysList);
		// 该区域下的所有企业
		List<Unit> units = reportService.queryNoUnits(unitId, roleId,
				String.valueOf(createYear == null ? "" : createYear.getYear()), sysId, repId);
		List<cn.com.generaldata.os.vo.UnitVO> unitsVo = new ArrayList<cn.com.generaldata.os.vo.UnitVO>();
		if (units != null && units.size() > 0) {
			for (Unit unit : units)
				unitsVo.add(unitService.toVo(unit));
			return unitsVo;
		}
		return null;
	}

	private ResultVO<ReportPerformVO> buildResult(List<ReportPerformVO> list) {
		ResultVO<ReportPerformVO> result = new ResultVO<ReportPerformVO>();
		result.setOperationResult(list);
		return result;
	}

	public ReportVersionYearRangeResult getReportVersionYearRange() {
		ReportVersionYearRangeResult result = new ReportVersionYearRangeResult();

		Date startYear = indicatorSystemSqlTemplate.queryForObject("SELECT MIN(start_date) FROM tbl_report_version",
				null, Date.class);
		Date endYear = indicatorSystemSqlTemplate.queryForObject("SELECT MAX(end_date) FROM tbl_report_version", null,
				Date.class);
		Calendar cal = Calendar.getInstance();
		cal.setTime(startYear);
		result.setStartYear(cal.get(Calendar.YEAR));
		cal.setTime(endYear);
		result.setEndYear(cal.get(Calendar.YEAR));
		return result;
	}

	/**
	 * 绩效评估.
	 * 
	 * @param year
	 * @param month
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/performance/evaluation")
	@Ok("jsp:/static/company/performance/list")
	public ResultVO<ReportPerformVO> performanceEvaluation(@Param("year") String year, @Param("month") String month,
			HttpServletRequest request, HttpSession session) {
		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = yearRange.getEndYear();
		List<Integer> years = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			years.add(i);
		}
		request.setAttribute("years", years);
		List<Integer> months = new ArrayList<Integer>();
		for (int i = 1; i <= 12; i++) {
			months.add(i);
		}
		request.setAttribute("months", months);
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String areaId = voUser.getUserAreaId();
		Calendar cal = Calendar.getInstance();
		if (year == null) {
			year = String.valueOf(cal.get(Calendar.YEAR));
		}
		if (month == null) {
			month = String.valueOf(cal.get(Calendar.MONTH) + 1);
		}
		request.setAttribute("selectYear", year);
		request.setAttribute("selectMonth", month);
		if (!"".equals(month)) {
			month = "/" + month;
		}
		List<ReportPerformVO> list = reportService.reportAccount(areaId, year + month, null);
		return buildResult(list);
	}

	@At("/report/myFillList")
	@Ok("jsp:/static/ocean/report/myFillList")
	public ResultVO<ReportVO> myFillList(@Param("p") int pageNum, @Param("chooseUser") String chooseUser,
			@Param("reportSystem") String reportSystem, @Param("reportDate") String reportDate,
			HttpServletRequest request, HttpSession session) {

		// 准备查询参数
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		// 报表制度列表，code是t_stat_system表的id，codename是name。
		List<SystemCodedic> systemList = this.queryType();
		request.setAttribute("systemList", systemList);
		// 初始进来的时候没有选择项，默认一个
		if (StringUtils.isBlank(reportSystem))
			reportSystem = systemList.get(0).getCode();
		String userId = voUser.getId(); // 当前用户ID
		String unitName = voUser.getUserUnit();// 用户所在单位名称
		String unitId = voUser.getUserUnitId();// 用户所在单位名称
		// 所选填报用户
		if (chooseUser != null) {
			userId = chooseUser;
			User userById = userService.queryUserById(chooseUser);
			unitName = userById.getUserUnit().getUnitName();
			unitId = userById.getUserUnit().getId();
		}
		request.setAttribute("unitName", unitName);
		request.setAttribute("chooseUser", userId);
		request.setAttribute("unitId", unitId);
		// 页数
		if (pageNum == 0) {
			pageNum = 1;
		}
		Date reportTime = new Date();
		// 报表时间
		if (StringUtils.isNotBlank(reportDate))
			try {
				reportTime = sfd.parse(reportDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		request.setAttribute("reportDate", sfd.format(reportTime));
		List<ReportVO> reportAllQuery = reportAllQuery(userId, reportSystem, reportTime);
		ResultVO<ReportVO> result = new ResultVO<ReportVO>();

		result.setOperationResult(reportAllQuery);
		result.setPageNumber(pageNum);
		result.setPageSize(1);
		result.setTotalCount(reportAllQuery.size());
		// Result<Report> xx = this.queryReportsByProxy(reportProxyId, userId,
		// (short) checkStatus, reportSystem,
		// reportTypeCode, reportVersion, startReportDate, endReportDate,
		// areaId, pageNum, flag, year, unitName);

		return result;
	}

	public List<ReportVO> reportAllQuery(String userId, String systemType, Date reportTime) {
		Calendar dateStart = Calendar.getInstance();
		Calendar dateEnd = Calendar.getInstance();
		Calendar dateNow = Calendar.getInstance();
		dateEnd.setTime(reportTime);
		dateStart.setTime(reportTime);
		dateStart.set(Calendar.DATE, 1);
		// 如果是当月
		if (dateNow.get(Calendar.YEAR) == dateStart.get(Calendar.YEAR)
				&& dateNow.get(Calendar.MONTH) == dateStart.get(Calendar.MONTH))
			dateEnd = Calendar.getInstance();
		else {
			int day = dateStart.getActualMaximum(Calendar.DAY_OF_MONTH);
			dateEnd.set(Calendar.DATE, day);
		}
		List<ReportVO> reportAllQuery = reportService.reportAllQuery(userId, systemType, dateStart.getTime(),
				dateEnd.getTime());

		return reportAllQuery;
	}

	/**
	 * 根据报表制度取得版本列表.
	 */
	@At("/report/getVersionList")
	@Ok("json")
	public List<cn.com.generaldata.jsme_indicator_system.entity.ReportVersion> getVersionList(
			@Param("systemId") int systemId) {

		// 版本
		List<cn.com.generaldata.jsme_indicator_system.entity.ReportVersion> versionList = versionWS
				.getVersionList(systemId);
		return versionList;
	}

	/**
	 * 根据版本ID取得报表类型列表.
	 */
	@At("/report/getReportTypeList")
	@Ok("json")
	public List<cn.com.generaldata.jsme_indicator_system.entity.ReportTypeNz> getReportTypeList(
			@Param("versionId") String versionId) {

		Class<cn.com.generaldata.jsme_indicator_system.entity.ReportTypeNz> clz = cn.com.generaldata.jsme_indicator_system.entity.ReportTypeNz.class;
		Dao tmpDao = Daos.ext(dao, FieldFilter.create(clz, "^id|typeName$"));
		List<cn.com.generaldata.jsme_indicator_system.entity.ReportTypeNz> reportTypeList = tmpDao.query(clz, Cnd
				.where("versionId", "=", versionId).asc("statSystem").asc("sortNo").asc("subSortNo"));
		return reportTypeList;

	}

	// 数据审核，审核，终审核,提交
	@At("/audit/finalsubmit")
	@Ok("json")
	public Map<String, String> batchChangeStatuss(@Param("ids") String ids, HttpServletRequest request,
			HttpSession session) {
		List<String> listIds = new ArrayList<String>();
		String[] id = ids.split(",");
		for (String addId : id) {
			if (addId.trim().length() == 0) {
				continue;
			}
			listIds.add(addId);
		}

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();
		Short checkStatus = 5;
		this.batchChangeStatus(checkStatus, listIds, userId, null);
		return CommonUtil.createOKMsg("上报成功");
	}

	// 报表提交
	@At("/report/submit")
	@Ok("json")
	public Map<String, String> batchChangeStatus(@Param("checkStatus") String checkStatus, @Param("ids") String ids,
			@Param("common") String common, HttpServletRequest request, HttpSession session) {
		List<String> listIds = new ArrayList<String>();
		String[] id = ids.split(",");
		for (String addId : id) {
			if (addId.trim().length() == 0) {
				continue;
			}
			listIds.add(addId);
		}

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();
		this.batchChangeStatus(Short.valueOf(checkStatus), listIds, userId, common);
		return CommonUtil.createOKMsg("操作成功");
	}

	// 数据审核，审核，报表查看
	@At("/audit/see")
	@Ok("jsp:/static/ocean/audit/shehebbchakan")
	public ResultVO<ReportVO> queryReportsByProxysss(@Param("sysId") String sysId, @Param("repId") String repId,
			@Param("vsId") String vsId, @Param("startingReportDate") Date startingReportDate,
			@Param("endingReportDate") Date endingReportDate, @Param("areaId") String areaId,
			@Param("p") Integer pageNum, @Param("createYear") String createYear, @Param("unitName") String unitName,
			@Param("staId") String staId, HttpServletRequest request, HttpSession session) {

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		//获取频率类型信息
		request.setAttribute("serviceIp", ip);
		//获取频率类型信息
		request.setAttribute("servicePort", port);
		request.setAttribute("serviceName", serviceName);
		String tvsId = "";
		String trepId = "";
		String tsysId = "";
		String tunitName = "";
		String tstaId = "";

		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("sysList", sysList);
		if (sysId == null) {
			tsysId = sysList.get(0).getCode();
		} else {
			tsysId = sysId;
		}
		//
		// List<ReportType> repList = new ArrayList<ReportType>();
		// if (createYear != null && sysId != null) {
		// Version vs = this.queryVersionByYear(createYear, sysId);
		// if (vs != null) {
		// repList = this.queryReportTypesByParam(String.valueOf(vs.getId()),
		// sysId);
		// }
		// request.setAttribute("repList", repList);
		// }
		List<ReportTypeVO> repList = new ArrayList<ReportTypeVO>();
		if (vsId != null && sysId != null) {

			//用海企业调查表
			if ("4".equals(sysId)) {
				repList = this.queryReportTypesSum(vsId, sysId);

			} else {
				repList = this.queryReportTypesByParam(vsId, sysId);
			}
		}
		request.setAttribute("repList", repList);
		// 年份是versionWS的getReportVersionYearRange查出所有版本的起始年到终止年。
		Calendar cal = Calendar.getInstance();
		String curYear = String.valueOf(cal.get(Calendar.YEAR));
		if (createYear == null && sysId == null) {
			request.setAttribute("curYear", curYear);
			createYear = curYear;
		}

		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = Integer.valueOf(curYear);
		List<Integer> yearList = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			yearList.add(i);
		}
		request.setAttribute("yearList", yearList);
		// 版本
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		vsList = this.queryReportVersion(sysId).getOperationResult();
		request.setAttribute("vsList", vsList);
		//
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();
		String userAreaId = voUser.getUserUnitId();
		request.setAttribute("userId", userId);

		if ("0".equals(vsId)) {
			tvsId = null;
		} else {
			tvsId = vsId;
		}
		if ("0".equals(repId)) {
			trepId = null;
		} else {
			trepId = repId;
		}
		if (unitName == null) {
			tunitName = "";
		} else {
			tunitName = unitName;
		}
		// 状态status
		List<Role> roleList = new ArrayList<Role>();
		Role rol = new Role();
		rol.setId("1");
		rol.setRoleName("已提交");
		roleList.add(rol);

		//		Role rol1 = new Role();
		//		rol1.setId("55");
		//		rol1.setRoleName("初审通过");
		//		roleList.add(rol1);

		Role rol2 = new Role();
		rol2.setId("3");
		rol2.setRoleName("审核驳回");
		roleList.add(rol2);

		Role rol3 = new Role();
		rol3.setId("5");
		rol3.setRoleName("审核通过");
		roleList.add(rol3);

		request.setAttribute("staList", roleList);
		//
		if (staId == null || "0".equals(staId)) {
			tstaId = "";
		} else {
			tstaId = staId;
		}
		//
		return this.queryAllReport(userAreaId, tunitName, tsysId, trepId, null, tvsId, startingReportDate,
				endingReportDate, pageNum, tstaId, createYear);

	}

	// 数据审核，审核，终审核
	@At("/audit/final")
	@Ok("jsp:/static/ocean/audit/shehezhshehe")
	public ResultVO<ReportVO> queryReportsByProxyss(@Param("sysId") String sysId, @Param("repId") String repId,
			@Param("vsId") String vsId, @Param("startingReportDate") Date startingReportDate,
			@Param("endingReportDate") Date endingReportDate, @Param("areaId") String areaId,
			@Param("p") Integer pageNum, @Param("createYear") String createYear, @Param("unitName") String unitName,
			HttpServletRequest request, HttpSession session) {

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		//获取频率类型信息
		request.setAttribute("serviceIp", ip);
		//获取频率类型信息
		request.setAttribute("servicePort", port);
		request.setAttribute("serviceName", serviceName);
		String tvsId = "";
		String trepId = "";
		String tsysId = "";
		String tunitName = "";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}

		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("sysList", sysList);
		if (sysId == null) {
			tsysId = sysList.get(0).getCode();
		} else {
			tsysId = sysId;
		}
		//
		// List<ReportType> repList = new ArrayList<ReportType>();
		// if (createYear != null && sysId != null) {
		// Version vs = this.queryVersionByYear(createYear, sysId);
		// if (vs != null) {
		// repList = this.queryReportTypesByParam(String.valueOf(vs.getId()),
		// sysId);
		// }
		// request.setAttribute("repList", repList);
		// }
		List<ReportTypeVO> repList = new ArrayList<ReportTypeVO>();
		if (vsId != null && sysId != null) {
			repList = this.queryReportTypesByParam(vsId, sysId);
		}
		request.setAttribute("repList", repList);
		// 年份是versionWS的getReportVersionYearRange查出所有版本的起始年到终止年。
		if (createYear == null && sysId == null) {
			Calendar cal = Calendar.getInstance();
			String curYear = String.valueOf(cal.get(Calendar.YEAR));
			request.setAttribute("curYear", curYear);
			createYear = curYear;
		}

		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = yearRange.getEndYear();
		List<Integer> yearList = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			yearList.add(i);
		}
		request.setAttribute("yearList", yearList);
		// 版本
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		vsList = this.queryReportVersion(sysId).getOperationResult();
		request.setAttribute("vsList", vsList);
		//
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();
		String userAreaId = voUser.getUserAreaId();
		request.setAttribute("userId", userId);

		if ("0".equals(vsId)) {
			tvsId = null;
		} else {
			tvsId = vsId;
		}
		if ("0".equals(repId)) {
			trepId = null;
		} else {
			trepId = repId;
		}
		if (unitName == null) {
			tunitName = "";
		} else {
			tunitName = unitName;
		}
		Short stats = 55;

		return toVoResultReport(reportService.queryReportsByProxy(userId, null, stats, tsysId, trepId, tvsId,
				startingReportDate, endingReportDate, userAreaId, pageNum, page, null, createYear, tunitName));

	}

	@At("/report/gpsFillList")
	@Ok("jsp:/static/ocean/report/gpsFillList")
	public void gpsFillList(@Param("chooseUser") String chooseUser, @Param("reportSystem") String reportSystem,
			@Param("reportDate") String reportDate, HttpServletRequest request, HttpSession session) {

		// 准备查询参数
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		// 报表制度列表，code是t_stat_system表的id，codename是name。
		List<SystemCodedic> systemList = this.queryType();
		request.setAttribute("systemList", systemList);
		// 初始进来的时候没有选择项，默认一个
		if (StringUtils.isBlank(reportSystem))
			reportSystem = systemList.get(0).getCode();
		String userId = voUser.getId(); // 当前用户ID
		String unitName = voUser.getUserUnit();// 用户所在单位名称
		String unitId = voUser.getUserUnitId();// 用户所在单位id

		// 所选填报用户
		if (chooseUser != null) {
			userId = chooseUser;
			User userById = userService.queryUserById(chooseUser);
			unitName = userById.getUserUnit().getUnitName();
			unitId = userById.getUserUnit().getId();
		}
		request.setAttribute("unitName", unitName);
		request.setAttribute("chooseUser", userId);
		request.setAttribute("unitId", unitId);

		Date reportTime = new Date();
		// 报表时间
		if (StringUtils.isNotBlank(reportDate))
			try {
				reportTime = sfd.parse(reportDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		request.setAttribute("reportDate", sfd.format(reportTime));
	}

	@At("/report/searchReport")
	@Ok("jsp:/static/ocean/report/gpsFillList")
	public ResultVO<ReportVO> searchReport(@Param("sysId") String sysId, @Param("repId") String repId,
			@Param("reportDate") String reportDate, @Param("startingReportDate") Date startingReportDate,
			@Param("endingReportDate") Date endingReportDate, @Param("chooseUser") String chooseUser,
			@Param("checkStatus") String checkStatus, @Param("p") Integer pageNum,
			@Param("createYear") String createYear, @Param("unitName") String unitName, HttpServletRequest request,
			HttpSession session) {

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		request.setAttribute("reportDate", reportDate);
		String tvsId = "";
		String trepId = "";
		String tsysId = "";
		String tunitName = "";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		// 准备查询参数
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId(); // 当前用户ID
		//				 unitName = voUser.getUserUnit();// 用户所在单位名称
		String unitId = voUser.getUserUnitId();// 用户所在单位id
		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("systemList", sysList);
		if (sysId == null) {
			tsysId = sysList.get(0).getCode();
		} else {
			tsysId = sysId;
		}
		Integer vsId = getVersionId(sysId, reportDate);
		List<ReportTypeVO> repList = new ArrayList<ReportTypeVO>();
		if (vsId != null && sysId != null) {
			repList = this.queryReportTypesByParam(vsId.toString(), sysId);
		}
		request.setAttribute("repList", repList);
		// 所选填报用户
		if (chooseUser != null) {
			User userById = userService.queryUserById(chooseUser);
			unitName = userById.getUserUnit().getUnitName();
			unitId = userById.getUserUnit().getId();
		}
		request.setAttribute("unitName", unitName);
		request.setAttribute("chooseUser", chooseUser);
		request.setAttribute("unitId", unitId);

		if (vsId == null) {
			tvsId = null;
		} else {
			tvsId = vsId.toString();
		}
		if ("0".equals(repId)) {
			trepId = null;
		} else {
			trepId = repId;
		}
		if (unitName == null) {
			tunitName = "";
		} else {
			tunitName = unitName;
		}
		Short stats = Short.valueOf(checkStatus);
		return toVoResultReport(reportService.queryReportsByProxy(userId, chooseUser, stats, tsysId, trepId, tvsId,
				startingReportDate, endingReportDate, voUser.getUserAreaId(), pageNum, page, null, createYear,
				tunitName));

	}

	// 数据审核，审核，初审核
	@At("/audit/init")
	@Ok("jsp:/static/ocean/audit/shehechushehe")
	public ResultVO<ReportVO> queryReportsByProxys(@Param("sysId") String sysId, @Param("repId") String repId,
			@Param("vsId") String vsId, @Param("startingReportDate") Date startingReportDate,
			@Param("endingReportDate") Date endingReportDate, @Param("areaId") String areaId,
			@Param("p") Integer pageNum, @Param("createYear") String createYear, @Param("unitName") String unitName,
			HttpServletRequest request, HttpSession session) {

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		//获取频率类型信息
		request.setAttribute("serviceIp", ip);
		//获取频率类型信息
		request.setAttribute("servicePort", port);
		request.setAttribute("serviceName", serviceName);
		String tvsId = "";
		String trepId = "";
		String tsysId = "";
		String tunitName = "";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}

		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("sysList", sysList);
		if (sysId == null) {
			tsysId = sysList.get(0).getCode();
		} else {
			tsysId = sysId;
		}
		List<ReportTypeVO> repList = new ArrayList<ReportTypeVO>();
		if (vsId != null && sysId != null) {
			repList = this.queryReportTypesByParam(vsId, sysId);
		}
		request.setAttribute("repList", repList);
		// 年份是versionWS的getReportVersionYearRange查出所有版本的起始年到终止年。
		Calendar cal = Calendar.getInstance();
		String curYear = String.valueOf(cal.get(Calendar.YEAR));
		if (createYear == null && sysId == null) {
			request.setAttribute("curYear", curYear);
			createYear = curYear;
		}

		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = Integer.valueOf(curYear);
		List<Integer> yearList = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			yearList.add(i);
		}
		request.setAttribute("yearList", yearList);
		// 版本
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		vsList = this.queryReportVersion(sysId).getOperationResult();
		request.setAttribute("vsList", vsList);
		//
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = voUser.getId();
		String userAreaId = voUser.getUserUnitId();
		request.setAttribute("userId", userId);

		if ("0".equals(vsId)) {
			tvsId = null;
		} else {
			tvsId = vsId;
		}
		if ("0".equals(repId)) {
			trepId = null;
		} else {
			trepId = repId;
		}
		if (unitName == null) {
			tunitName = "";
		} else {
			tunitName = unitName;
		}
		Short stats = 1;
		return toVoResultReport(reportService.queryReportsByProxy(userId, null, stats, tsysId, trepId, tvsId,
				startingReportDate, endingReportDate, userAreaId, pageNum, page, null, createYear, tunitName));

	}

	@At("/monitor/changeXl")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> queryReportTypesByParas(@Param("industryId") String industryId,
			@Param("code") String code, @Param("date") String date) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		if (StringUtils.isNotBlank(industryId)) {
			List<SystemCodedic> queryType = queryType();
			List<cn.com.generaldata.os.newpojo.ReportType> queryReportTypeByIndustryId = reportService
					.queryReportTypeByIndustryId(industryId);
			for (cn.com.generaldata.os.newpojo.ReportType pReportType : queryReportTypeByIndustryId) {
				ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
				if (voReportType != null && voReportType.getTypeCode() != null) {
					if (code != null && !"".equals(code)) {
						if (code.equals(voReportType.getTypeCode())) {
							Integer version = getVersionId(code, date);
							if (version != null) {
								if (version.toString().equals(voReportType.getVersionId())) {
									reportTypes.add(voReportType);
								}
							} else {
								reportTypes.add(voReportType);
							}
						}
					}
					//					else {
					//						if (version != null && !"".equals(version)) {
					//							if (version.equals(voReportType.getVersionId())) {
					//								reportTypes.add(voReportType);
					//							}
					//						} else {
					//							reportTypes.add(voReportType);
					//						}
					//					}
				}
			}
		}

		Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {

			@Override
			public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
				return rt1.getTypeCode().compareTo(rt2.getTypeCode());
			}
		});
		return reportTypes;
	}

	@At("/monitor/changeSys")
	@Ok("json")
	@Filters
	public List<VersionVO> getVersionList2(@Param("id") String id) {
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		return this.queryReportVersion(id).getOperationResult();
	}

	@At("/monitor/changeSysToData")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> getRepListBySys(@Param("id") String id) {
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		vsList = this.queryReportVersion(id).getOperationResult();
		String tempId = vsList.get(0).getId();
		List<ReportTypeVO> rpList = this.queryReportTypesByParam(tempId, id);
		return rpList;
	}

	private Integer getVersionId(String sysId, String date) {
		Date reportTime = new Date();
		// 报表时间
		if (StringUtils.isNotBlank(date))
			try {
				reportTime = sfd.parse(date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		Integer vsId = versionWS.getReportVersion(sysId, reportTime);
		return vsId;
	}

	@At("/monitor/changeRsForDate")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> changeRsForDate(@Param("sysId") String sysId, @Param("date") String date) {

		List<ReportTypeVO> rpList = null;
		Integer vsId = getVersionId(sysId, date);
		if (vsId == null)
			return rpList;
		rpList = this.queryReportTypesByParam(vsId.toString(), sysId);

		return rpList;
	}

	@At("/monitor/changeRsToData")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> changeRsToData(@Param("sysId") String sysId, @Param("vsId") String vsId) {
		List<ReportTypeVO> rpList = null;

		rpList = this.queryReportTypesByParam(vsId, sysId);

		return rpList;
	}

	@At("/monitor/changeVsToData")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> getRepListByVersion(@Param("sysId") String sysId, @Param("vsId") String vsId) {

		List<ReportTypeVO> rpList = null;

		//用海企业调查表
		if ("4".equals(sysId)) {
			rpList = this.queryReportTypesSum(vsId, sysId);

		} else {
			rpList = this.queryReportTypesByParam(vsId, sysId);
		}

		return rpList;
	}

	@At("/monitor/changeDl")
	@Ok("json")
	@Filters
	public List<cn.com.generaldata.os.vo.IndustryVO> getXl(@Param("dlId") String dlId) {
		List<cn.com.generaldata.os.vo.IndustryVO> cateList = new ArrayList<cn.com.generaldata.os.vo.IndustryVO>();
		List<cn.com.generaldata.os.vo.IndustryVO> catesList = new ArrayList<cn.com.generaldata.os.vo.IndustryVO>();

		catesList = industryWS.queryAllDLIndustries().getOperationResult();
		for (cn.com.generaldata.os.vo.IndustryVO indus : catesList) {
			if (dlId.equals(indus.getCode())) {
				cateList.add(indus);
			}
		}

		return cateList;
	}

	// 2014-9-28
	@At("/monitor/expReps")
	@Ok("void")
	public void getExportUrl(@Param("roleId") String roleId, @Param("createYear") Date year,
			@Param("sysId") String typeId, @Param("repId") String reportType, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) {
		List<cn.com.generaldata.os.vo.UnitVO> unitList = this.queryNoUnits(roleId, year, typeId, reportType, request,
				session);
		List<String> ids = new ArrayList<String>();

		OutputStream out = null;
		try {
			out = response.getOutputStream();

			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String encodedfileName = dateStr + ".xls";
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");

			if (unitList != null && unitList.size() > 0) {
				for (cn.com.generaldata.os.vo.UnitVO unit : unitList)
					ids.add(unit.getId());

				unitService.generalExcel(ids, out);

			}
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			Streams.safeClose(out);
		}

	}

	@At("/monitor/setcalls")
	@Ok("jsp:/static/ocean/monitor/datacalls")
	public void initSetCalls(@Param("title") String title, @Param("content") String content,
			HttpServletRequest request, HttpSession session) {
		// 报表制度就是reportWS的queryType查出所有制度
		List<SystemCodedic> sysList = this.queryType();
		request.setAttribute("sysList", sysList);
		// 版本
		List<VersionVO> vsList = new ArrayList<VersionVO>();
		vsList = this.queryReportVersion(null).getOperationResult();
		request.setAttribute("vsList", vsList);

		String tempId = vsList.get(0).getId();
		List<ReportTypeVO> rpList = this.queryReportTypesByParam(tempId, "1");
		request.setAttribute("rpList", rpList);

		//获取频率类型信息
		request.setAttribute("reportTimetype", cacheManager.getReportTimetype());
		Date reportTime = new Date();
		request.setAttribute("reportDate", sfd.format(reportTime));
		// 类别
		List<cn.com.generaldata.os.vo.IndustryVO> cateList = new ArrayList<cn.com.generaldata.os.vo.IndustryVO>();
		cateList = industryWS.queryAllDLIndustries().getOperationResult();
		request.setAttribute("cateList", cateList);
		// 大类
		List<cn.com.generaldata.os.vo.IndustryVO> dlList = new ArrayList<cn.com.generaldata.os.vo.IndustryVO>();
		cn.com.generaldata.os.vo.IndustryVO ind1 = new cn.com.generaldata.os.vo.IndustryVO();
		cn.com.generaldata.os.vo.IndustryVO ind2 = new cn.com.generaldata.os.vo.IndustryVO();
		cn.com.generaldata.os.vo.IndustryVO ind3 = new cn.com.generaldata.os.vo.IndustryVO();
		ind1.setCode("1");
		ind1.setDustryName("主要海洋产业");
		dlList.add(ind1);
		ind2.setCode("2");
		ind2.setDustryName("海洋科研教育管理服务业");
		dlList.add(ind2);
		ind3.setCode("3");
		ind3.setDustryName("海洋相关产业");
		dlList.add(ind3);
		request.setAttribute("dlList", dlList);
		// session取得areaId
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String areaId = voUser.getUserAreaId();

		List<cn.com.generaldata.os.vo.UnitVO> unitList = unitWS.queryAllUsersByIndustryId(null, areaId);
		request.setAttribute("unitList", unitList);

	}

	@SuppressWarnings("unchecked")
	public void batchChangeStatus(Short checkStatus, List<String> ids, String operatorId, String common) {
		if (checkStatus != null && ids != null && ids.size() > 0) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", arrIds));
			List<cn.com.generaldata.os.pojo.Report> reports = (List<cn.com.generaldata.os.pojo.Report>) reportService
					.queryReports(filter, null).getOperationResult();

			for (cn.com.generaldata.os.pojo.Report report : reports) {
				report.setReportCheckStatus(checkStatus);

				if (common != null) {
					report.setReportCheckComment(common);
				}
				User operator = userService.queryUserById(operatorId);
				report.setOperator(operator);
				// FLAG_PASSED=6:总局审核通过
				// FLAG_PROVINCE_PASSED_UNCOMMITTED=2:省审核通过企业上报未提交总局
				if (checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PASSED).shortValue()
						|| checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_UNCOMMITTED)
								.shortValue()) {
					report.setReportCheckSuccessDate(new Date());
				}
				// 如果是本级海洋局用户提交直接提交上级(内网肯定是海洋局用户填报)或者代填的
				if (checkStatus.shortValue() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) {
					report.setReportCheckStatus(ReportConstant.FLAG_PROVINCE_PASSED_COMMITTED);
				}
				// 改变报表的状态
				reportService.modifyReport(report);
				String comment = report.getReportCheckResult();

				// 记录历史，并进行留痕操作
				// FLAG_PASSED=6:总局审核通过
				if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PRE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_UNCOMMITTED
					comment = "初审通过";
					// 2; 省审核通过企业上报未提交总局
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_REJECTED)
						.shortValue()) { // FLAG_PROVINCE_REJECTED
					// //省驳回企业上报
					comment = "驳回报表";
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) { // FLAG_COMMITTED
					comment = "提交报表,待审核";
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_COMMITTED
					comment = "提交报表,待审核";
					if (reportService.checkOperatorIsBest(report.getOperator().getId()))
						comment = "审核通过";
				}
				reportService.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
						report.getReportCheckStatus(), report.getArea().getId());
				historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null, report.getOperator(),
						report, report.getReportCheckStatus(), report.getReportCheckComment(), comment, new Date()));
			}
		}
	}

	@At("/data/preImport")
	@Ok("jsp:/static/ocean/report/uploadReport")
	public void preImport(@Param("unitId") String unitId, @Param("reportProxyId") String reportProxyId,
			@Param("reportTypeId") String reportTypeId, @Param("timeType") String timeType,
			@Param("yearType") String yearType, @Param("quarterDate") String quarterDate,
			@Param("timeDate") String timeDate, @Param("status") String status, HttpServletRequest request) {
		request.setAttribute("unitId", unitId);
		request.setAttribute("reportProxyId", reportProxyId);
		request.setAttribute("reportTypeId", reportTypeId);
		request.setAttribute("timeType", timeType);
		request.setAttribute("yearType", yearType);
		request.setAttribute("quarterDate", quarterDate);
		request.setAttribute("timeDate", timeDate);
		request.setAttribute("status", status);
	}

	@At("/data/preMutiImport")
	@Ok("jsp:/static/ocean/report/mutiImportReport")
	public void preMutiImport(@Param("unitId") String unitId, @Param("reportProxyId") String reportProxyId,
			@Param("reportTypeId") String reportTypeId, @Param("timeType") String timeType,
			@Param("yearType") String yearType, @Param("quarterDate") String quarterDate,
			@Param("timeDate") String timeDate, @Param("status") String status, HttpServletRequest request) {
		request.setAttribute("unitId", unitId);
		request.setAttribute("reportProxyId", reportProxyId);
		request.setAttribute("reportTypeId", reportTypeId);
		request.setAttribute("timeType", timeType);
		request.setAttribute("yearType", yearType);
		request.setAttribute("quarterDate", quarterDate);
		request.setAttribute("timeDate", timeDate);
		request.setAttribute("status", status);
	}

	/*
	 * 注释"@Param("Filedata ") List<TempFile>  tempFiles," 中的Filedata是客户端 <input
	 * type =" Filedata " name =" Filedata " id ="file" /> 中的name名
	 */
	@At("/data/mutiUpload")
	@AdaptBy(type = UploadAdaptor.class)
	public String upload(@Param("uploadFile") TempFile uploadFile, HttpServletRequest req, ServletContext context,
			HttpSession session) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String userId = req.getParameter("id");
		String ext = uploadFile.getMeta().getFileExtension();
		String name = uploadFile.getMeta().getFileLocalName();
		File file = uploadFile.getFile();
		String multi = importReportMulti(voUser.getId(), file, name, ext);
		return multi;
	}

	// 导入报表
	@At("/data/uploadReport")
	@AdaptBy(type = UploadAdaptor.class)
	@POST
	@Ok("jsp:/static/ocean/unit/uploadOk")
	public void uploadReport(@Param("uploadFile") TempFile uploadFile, @Param("unitId") String unitId,
			@Param("reportProxyId") String reportProxyId, @Param("reportTypeId") String reportTypeId,
			@Param("timeType") String timeType, @Param("yearType") String yearType,
			@Param("quarterDate") String quarterDate, @Param("timeDate") String timeDate,
			@Param("status") String status, ServletContext context, HttpServletRequest request) {

		if (uploadFile == null) {
			request.setAttribute("msg", "请选择文件。");
			return;
		}

		String folderPath = properties.getProperty("fileUploadPath").trim();

		String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String ext = uploadFile.getMeta().getFileExtension();
		// 上传文件类型
		String fileType = properties.getProperty("fileType").trim();
		String[] split = fileType.split("\\|");
		Boolean extNo = false;
		for (String str : split) {
			if (str.equals(ext)) {
				extNo = true;
				break;
			}
		}
		if (!extNo) {
			request.setAttribute("msg", "请选择正确报表文件。");
			return;
		}
		String newFileName = timeStr + ext;
		moveFile(uploadFile.getFile(), folderPath + newFileName);
		String importReport = importReport(unitId, reportProxyId, reportTypeId, timeType, yearType, timeDate, "", "",
				quarterDate, new File(folderPath + newFileName), status);
		request.setAttribute("msg", importReport);
	}

	/**
	 * 查看用户能否填报报表
	 * @param idStr
	 * @return
	 */
	@At("/report/userReport")
	@Ok("json")
	public Map<String, String> userReport(@Param("uid") String uid, @Param("typeId") String typeId) {

		boolean result = false;
		if (StringUtil.isBlank(typeId))
			result = true;
		else
			result = reportService.checkUserReport(uid, typeId);
		if (result) {
			return CommonUtil.createOKMsg("ok");
		} else {
			return CommonUtil.createNGMsg("error");
		}
	}
}
